LeetCode39 组合总和
题目
给定一个无重复元素的数组 candidates 和一个目标数 target ,找出candidates 中所有可以使数字和为 target 的组合。
candidates 中的数字可以无限制重复被选取。
说明:
所有数字(包括 target)都是正整数。
解集不能包含重复的组合。
示例 1:
输入:candidates = [2,3,6,7], target = 7,
所求解集为:
[
[7],
[2,2,3]
]
示例 2:
输入:candidates = [2,3,5], target = 8,
所求解集为:
[
[2,2,2,2],
[2,3,3],
[3,5]
]
提示:
1 <= candidates.length <= 30
1 <= candidates[i] <= 200
candidate 中的每个元素都是独一无二的。
1 <= target <= 500
方法
回溯
- 时间复杂度:O(s),s是所有可行解总和
- 空间复杂度:O(target),取决于递归栈的大小,最坏情况为target
class Solution {
private List<List<Integer>> result = new ArrayList<>();
private List<Integer> tmp = new ArrayList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
if(target==0){
result.add(new ArrayList<Integer>(tmp));
} else if(target>0){
for(int i=0;i<candidates.length;i++){
int c = candidates[i];
tmp.add(c);
combinationSum(Arrays.copyOfRange(candidates,i,candidates.length),target-c);
tmp.remove(tmp.size()-1);
}
}
return result;
}
}
class Solution {
private List<List<Integer>> result = new ArrayList<>();
private List<Integer> temp = new ArrayList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
dfs(candidates,target,0);
return result;
}
private void dfs(int[] candidates,int target,int depth){
if(depth==candidates.length){
return;
}
if(target==0){
result.add(new ArrayList<>(temp));
return;
}
//选当前数
if(candidates[depth]<=target){
temp.add(candidates[depth]);
dfs(candidates, target-candidates[depth], depth);
temp.remove(temp.size()-1);
}
//不选当前数
dfs(candidates, target, depth+1);
}
}
动态规划
- 时间复杂度:O()
- 空间复杂度:O()
分类:
LeetCode Hot100
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理