LeetCode-40. Combination Sum IIhttps://leetcode.com/problems/combination-sum-ii/
题目描述
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
解题思路
【C++】
class Solution {
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
vector<vector<int>> res;
vector<int> combinations;
bactracking(candidates, res, combinations, target, 0);
return res;
}
void bactracking(vector<int>& candidates, vector<vector<int>> &res,
vector<int> &combinations, int target, int index) {
if (target == 0) {
res.push_back(combinations);
return ;
}
for (int i = index; i < candidates.size() && candidates[i] <= target; ++i) {
if (notRepeated(candidates, index, i) ) {
combinations.push_back(candidates[i]);
bactracking(candidates, res, combinations, target - candidates[i], i + 1);
combinations.pop_back();
}
}
}
bool notRepeated(vector<int>& nums, int begin, int end) {
if (begin == end) return true;
for (int i=begin; i<end; ++i) if(nums[i] == nums[end]) return false;
return true;
}
};
【Java】
class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
List<List<Integer>> res = new ArrayList<>();
bactracking(candidates, res, new ArrayList<Integer>(), target, 0);
return res;
}
void bactracking(int[] candidates, List<List<Integer>> res,
List<Integer> combinations, int target, int index) {
if (target == 0) {
res.add(new ArrayList<>(combinations));
return ;
}
for (int i = index; i < candidates.length && candidates[i] <= target; ++i) {
if (notRepeated(candidates, index, i)) {
combinations.add(candidates[i]);
bactracking(candidates, res, combinations, target - candidates[i], i + 1);
combinations.remove(combinations.size()-1);
}
}
}
boolean notRepeated(int[] nums, int begin, int end) {
if (begin == end) return true;
for (int i=begin; i<end; ++i) if(nums[i] == nums[end]) return false;
return true;
}
}