Leetcode 题目解析之 Combination Sum II
【摘要】 Leetcode 题目解析之 Combination Sum II
Given a collection of candidate numbers © and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
Note:
- All numbers (including target) will be positive integers.
- Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
- The solution set must not contain duplicate combinations.
For example, given candidate set 10,1,2,7,6,1,5 and target 8,
A solution set is:
1, 7
1, 2, 5
2, 6
1, 1, 6
- Combination Sum每个元素可以使用多次,所以递归是dfs(i, target - candidatesi, result, cur, candidates);
- Combination Sum II每个元素只能使用一次,所以递归是dfs(i + 1, target - candidatesi, rt, cur, candidates);因为解可能重复,所以使用set,最后转成list。
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
if (candidates == null || candidates.length == 0) {
return new ArrayList<List<Integer>>();
}
Set<List<Integer>> rt = new HashSet<List<Integer>>();
ArrayList<Integer> cur = new ArrayList<Integer>();
Arrays.sort(candidates);
dfs(0, target, rt, cur, candidates);
return new ArrayList<List<Integer>>(rt);
}
private void dfs(int start, int target, Set<List<Integer>> rt,
ArrayList<Integer> cur, int[] candidates) {
if (target == 0) {
rt.add(new ArrayList<Integer>(cur));
return;
}
for (int i = start; i < candidates.length; i++) {
// candidates[i] > target,则递归结束,后面不可能是解
if (candidates[i] > target) {
return;
}
cur.add(candidates[i]);
dfs(i + 1, target - candidates[i], rt, cur, candidates);
cur.remove(cur.size() - 1);
}
}
【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)