Combinations in C++



Suppose we have two integers n and k. We have to find all possible combinations of k numbers out of 1 ... n. So if n = 4 and k = 2, then the combinations will be [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]

To solve this, we will follow these steps −

  • We will use recursive function to solve this. the function solve() is taking n, k, temp array and start. The start is initially 1. This will act like
  • if size of temp array = k, then insert temp into res array, and return
  • for i := start to n,
    • insert i into temp
    • solve(n, k, temp, i + 1)
    • remove one element from the end of temp
  • call the solve function like solve(n, k, [])
  • return res

Example

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<vector<int> > v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << "[";
      for(int j = 0; j <v[i].size(); j++){
         cout << v[i][j] << ", ";
      }
      cout << "],";
   }
   cout << "]"<<endl;
}
class Solution {
public:
   vector < vector <int> > res;
   void solve(int n, int k, vector <int> temp, int start = 1){
      if(temp.size() == k){
         res.push_back(temp);
         return;
      }
      for(int i = start; i <= n; i++){
         temp.push_back(i);
         solve(n, k, temp, i + 1);
         temp.pop_back();
      }
   }
   vector<vector<int> > combine(int n, int k) {
      res.clear();
      vector <int> temp;
      solve(n ,k, temp);
      return res;
   }
};
main(){
   Solution ob;
   print_vector(ob.combine(5,3));
}

Input

5
3

Output

[[1,2,3],[1,2,4],[1,2,5],[1,3,4],[1,3,5],[1,4,5],[2,3,4],[2,3,5],[2,4,5],[3,4,5]]

Advertisements