Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 952c079

Browse files
commit
1 parent c0a48f6 commit 952c079

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

‎40. Combination Sum IIcpp

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class Solution {
2+
public:
3+
4+
void combination(int index, int arrSize, int currSum, int target, vector<int>& ds, vector<vector<int>>& ans, vector<int> & arr) {
5+
if(currSum > target) return;
6+
7+
if(currSum == target){
8+
ans.push_back(ds);
9+
return;
10+
}
11+
12+
for(int i = index; i < arrSize; i++){
13+
if(i > index && arr[i] == arr[i-1]) continue; // skip duplicates
14+
if(currSum + arr[i] > target) break; // pruning
15+
16+
ds.push_back(arr[i]);
17+
combination(i + 1, arrSize, currSum + arr[i], target, ds, ans, arr); // i+1 because each element can be used once
18+
ds.pop_back();
19+
}
20+
}
21+
22+
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
23+
vector<vector<int>> ans;
24+
vector<int> ds;
25+
sort(candidates.begin(), candidates.end()); // sort to handle duplicates and pruning
26+
combination(0, candidates.size(), 0, target, ds, ans, candidates);
27+
return ans;
28+
}
29+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /