Skip to content

Commit 2c78d72

Browse files
committed
combination sum 2
1 parent e4838bf commit 2c78d72

File tree

2 files changed

+66
-1
lines changed

2 files changed

+66
-1
lines changed
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
/*
2+
Combination Sum II
3+
==================
4+
5+
Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target.
6+
7+
Each number in candidates may only be used once in the combination.
8+
9+
Note: The solution set must not contain duplicate combinations.
10+
11+
Example 1:
12+
Input: candidates = [10,1,2,7,6,1,5], target = 8
13+
Output:
14+
[
15+
[1,1,6],
16+
[1,2,5],
17+
[1,7],
18+
[2,6]
19+
]
20+
21+
Example 2:
22+
Input: candidates = [2,5,2,1,2], target = 5
23+
Output:
24+
[
25+
[1,2,2],
26+
[5]
27+
]
28+
29+
Constraints:
30+
1 <= candidates.length <= 100
31+
1 <= candidates[i] <= 50
32+
1 <= target <= 30
33+
*/
34+
35+
class Solution
36+
{
37+
public:
38+
void dfs(vector<int> &arr, int i, int tar, vector<int> atn, vector<vector<int>> &ans)
39+
{
40+
if (tar < 0)
41+
return;
42+
if (tar == 0)
43+
{
44+
ans.push_back(atn);
45+
return;
46+
}
47+
48+
for (int j = i; j < arr.size(); ++j)
49+
{
50+
if (j != i && arr[j] == arr[j - 1])
51+
continue;
52+
atn.push_back(arr[j]);
53+
dfs(arr, j + 1, tar - arr[j], atn, ans);
54+
atn.pop_back();
55+
}
56+
}
57+
58+
vector<vector<int>> combinationSum2(vector<int> &arr, int target)
59+
{
60+
vector<vector<int>> ans;
61+
sort(arr.begin(), arr.end());
62+
dfs(arr, 0, target, {}, ans);
63+
return ans;
64+
}
65+
};

Striver Sheet/README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@
7878
- [Subset Sums](https://practice.geeksforgeeks.org/problems/subset-sums2234/1#) - [Cpp Soultion](./Day-9/Subset%20Sums.cpp)
7979
- [Subsets II](https://leetcode.com/problems/subsets-ii/) - [Cpp Soultion](./Day-9/Subsets%20II.cpp)
8080
- [Combination Sum](https://leetcode.com/problems/combination-sum/) - [Cpp Soultion](./Day-9/Combination%20Sum.cpp)
81-
- []() - [Cpp Soultion](./Day-9/.cpp)
81+
- [Combination Sum II](https://leetcode.com/problems/combination-sum-ii/) - [Cpp Soultion](./Day-9/Combination%20Sum%20II.cpp)
8282
- []() - [Cpp Soultion](./Day-9/.cpp)
8383
- []() - [Cpp Soultion](./Day-9/.cpp)
8484

0 commit comments

Comments
 (0)