Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

interviewbit: combinational sum2 #80

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 22 additions & 36 deletions Backtracking/CombinationSumII.cpp
Original file line number Diff line number Diff line change
@@ -1,44 +1,30 @@
void make(vector<int>& A, int curr, int currSum, int sum, vector<int> temp, vector<vector<int> >& ans, map<vector<int>, bool>& m){
if(currSum > sum){
return;
}
else if(currSum == sum){
if(m.find(temp) == m.end()){
m[temp] = true;
ans.push_back(temp);
}
void back_track(vector<vector<int>> &ans, vector<int> &combination, vector<int>& candidates, int start, int target) {
if (target == 0) {
ans.push_back(combination);
return;
}

for(int i = curr; i < A.size(); i++){
vector<int> t(temp);
t.push_back(A[i]);
make(A, i+1, currSum+A[i], sum, t, ans, m);

for ( int i = start; i < candidates.size(); i++) {
if ((target - candidates[i]) < 0)
return;
if (candidates[i] <= target) {
combination.push_back(candidates[i]);
back_track(ans, combination, candidates, i + 1, target - candidates[i]);
combination.pop_back();
while(i+1<candidates.size() && candidates[i]==candidates[i+1]) {
i++;
}
}
}
}

vector<vector<int> > Solution::combinationSum(vector<int> &A, int B) {
// Do not write main() function.
// Do not read input, instead use the arguments to the function.
// Do not print the output, instead return values as specified
// Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details

vector<vector<int> > ans;

int n = A.size();

if(A.size() == 0){
return ans;
}

vector<vector<int>> ans;
vector<int> combination;
vector<int>::iterator ip;

sort(A.begin(), A.end());
map<vector<int>, bool> m;
back_track(ans, combination, A, 0, B);

for(int i = 0; i < n; i++){
vector<int> temp;
temp.push_back(A[i]);
make(A, i+1, A[i], B, temp, ans, m);
}

return ans;
}
return ans;
}