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()
posted @   你也要来一颗长颈鹿吗  阅读(24)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
点击右上角即可分享
微信分享提示