LeetCode 40. Combination Sum II
LeetCode 40. Combination Sum II (组合总和 II)
题目
链接
https://leetcode.cn/problems/combination-sum-ii/
问题描述
给定一个候选人编号的集合 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的每个数字在每个组合中只能使用 一次 。
注意:解集不能包含重复的组合。
示例
输入: candidates = [10,1,2,7,6,1,5], target = 8,
输出:
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]
提示
1 <= candidates.length <= 100
1 <= candidates[i] <= 50
1 <= target <= 30
思路
这里i>index,就代表是同一层,同一层不能采用相同的数,那么就可以跳过,别的思路和之前一题一样。
复杂度分析
时间复杂度 O(n2)
空间复杂度 O(n)
代码
Java
List<List<Integer>> ans = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
trace(0, target, candidates, 0);
return ans;
}
public void trace(int sum, int target, int[] candidates, int index) {
if (sum > target) {
return;
}
if (sum == target) {
ans.add(new LinkedList<>(path));
return;
}
for (int i = index; i < candidates.length; i++) {
if (i > index && candidates[i] == candidates[i - 1]) {
continue;
}
path.add(candidates[i]);
sum += candidates[i];
trace(sum, target, candidates, i + 1);
sum -= candidates[i];
path.removeLast();
}
}
分类:
LeetCode(Java)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!