40. Combination Sum II
1. Description
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.
2. Note
- The solution set must not contain duplicate combinations.
3. Example
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]
]
4. Constraints
- 1 <= candidates.length <= 100
- 1 <= candidates[i] <= 50
- 1 <= target <= 30
5. Solutions
My Accepted Solution
n = m_candidates.size()
Time complexity : O($2^nn$)
Space complexity : O(n)
class Solution {
public:
void combinationSum(
const vector<int>& i_candidates,
vector<int>& m_subarray,
vector<vector<int>>& o_output,
int target,
int index) {
for (int beginning = index; index < i_candidates.size(); index++) {
if (index != beginning && i_candidates[index] == i_candidates[index - 1]) {
continue;
}
if (target < i_candidates[index]) {
break;
} else if (target == i_candidates[index]) {
m_subarray.push_back(i_candidates[index]);
o_output.push_back(m_subarray);
m_subarray.pop_back();
break;
} else if (target > i_candidates[index]) {
m_subarray.push_back(i_candidates[index]);
combinationSum(
i_candidates,
m_subarray,
o_output,
target - i_candidates[index],
index + 1);
m_subarray.pop_back();
}
}
}
// vector<vector<int>> combinationSum2(vector<int>& candidates, int target)
vector<vector<int>> combinationSum2(vector<int>& m_candidates, int target) {
vector<int> subArray;
vector<vector<int>> combinations;
sort(m_candidates.begin(), m_candidates.end());
combinationSum(m_candidates, subArray, combinations, target, 0);
return combinations;
}
};