Combination Sum IIII in C++


Consider we have to generate all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used. Each combination should be a unique set of numbers. All numbers should be positive, and the solution must not contain duplicate combinations. So if k = 3 and n = 9, then the possible combinations are [[1,2,6],[1,3,5],[2,3,4]]

To solve this, we will follow these steps −

  • Suppose we will solve this using forming a method called solve. This will be recursive method, this will take k, n, temp array, and start. the start is initially 1

  • if n = 0

    • if size of temp = k, then insert temp into res and return

    • for i := start to minimum of 9 and n

      • insert i into temp

      • solve(k, n – i, temp, i + 1)

      • delete the last element from temp

  • The main method will be like

  • create one blank vector called temp

  • solve(k, n, temp)

  • return res

Example

Let us see the following implementation to get better understanding −

class Solution {
   public:
   vector < vector <int> > res;
   void solve(int k, int n, vector <int> temp, int start = 1){
      if(n == 0){
         if(temp.size() == k){
            res.push_back(temp);
         }
         return;
      }
      for(int i = start ; i <= min(9, n); i++){
         temp.push_back(i);
         solve(k, n - i, temp, i + 1);
         temp.pop_back();
      }
   }
   vector<vector<int>> combinationSum3(int k, int n) {
      res.clear();
      vector <int> temp;
      solve(k, n, temp);
      return res;
   }
};

Input

3
9

Output

[[1,2,6],[1,3,5],[2,3,4]]
raja
Published on 05-Feb-2020 10:07:39
Advertisements