Combination Sum II in C++

C++Server Side ProgrammingProgramming

Suppose we have a set of candidate numbers (all elements are unique) and a target number. We have to find all unique combinations in candidates where the candidate numbers sum to the given target. The same number will not be chosen from candidates more than once. So if the elements are [2,3,6,7,8] and the target value is 8, then the possible output will be [[2,6],[8]]

Let us see the steps −

  • We will solve this in recursive manner. The recursive function is named as solve(). This takes index, an array a, the integer b and another array temp. The solve method will work like below −
  • Define empty array res
  • if b = 0, then insert temp into res, and return
  • if index = size of a, then return
  • if b < 0, then return
  • sort the array a
  • for i in range index to size of a – 1
    • if i > index and a[i] = a[i – 1], then continue
    • insert a[i] into temp
    • solve(i + 1, a, b – a[i], temp)
    • delete last element from temp
  • call the solve() method by passing index = 0, array a, and target b, and another array temp
  • return res

Let us see the following implementation to get better understanding −

Example

 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 idx, vector <int> &a, int b, vector <int> temp){
      if(b == 0){
         res.push_back(temp);
         return;
      }
      if(idx == a.size())return;
      if(b < 0)return;
      sort(a.begin(), a.end());
      for(int i = idx; i < a.size(); i++){
         if(i > idx && a[i] == a[i-1])continue;
         temp.push_back(a[i]);
         solve(i + 1, a, b - a[i], temp);
         temp.pop_back();
      }
   }
   vector<vector<int> > combinationSum2(vector<int> &a, int b) {
      res.clear();
      vector <int> temp;
      solve(0, a, b, temp);
      return res;
   }
};
main(){
   Solution ob;
   vector<int> v = {2,3,6,7,8};
   print_vector(ob.combinationSum2(v, 10)) ;
}

Input

[2,3,6,7,8]
8

Output

[[2, 8, ],[3, 7, ],]
raja
Published on 03-Feb-2020 12:21:20
Advertisements