40. Combination Sum II
Problem Statement
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
.
Each number in candidates
may only be used once in the combination.
Note: The solution set must not contain duplicate combinations.
Example 1:
Input: candidates = [10,1,2,7,6,1,5], target = 8
Output:
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]
Example 2:
Input: candidates = [2,5,2,1,2], target = 5
Output:
[
[1,2,2],
[5]
]
Constraints:
1 <= candidates.length <= 100
1 <= candidates[i] <= 50
1 <= target <= 30
Intuition
Approach:
Do unique values, can make use of set, but gives TLE
So,
We Pick element at one index, only once
Like,
1 1 2 3
If at once we pick 1, we dont pick it again until next iteration
Links
https://leetcode.com/problems/combination-sum-ii/description/
Video Links
https://www.youtube.com/watch?v=G1fRTGRxXU8&t=1244s&ab_channel=takeUforward
Approach 1:
class Solution {
public:
vector<vector<int>> ans;
void find_comb(vector<int>& cand, int target, int index, vector<int> &temp){
if(target == 0){
ans.push_back(temp);
return ;
}
for(int i=index; i<cand.size(); i++){
if(i > index and cand[i-1] == cand[i])
continue;
if(cand[i] > target) break;
temp.push_back(cand[i]);
find_comb(cand, target-cand[i], i+1, temp);
temp.pop_back();
}
}
vector<vector<int>> combinationSum2(vector<int>& cand, int target) {
vector<int> temp;
sort(cand.begin(), cand.end());
find_comb(cand, target, 0, temp);
return ans;
}
};
Approach 2:
Approach 3:
Approach 4:
Similar Problems
Last updated