ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

Leetcode 39 组合总和

2026/9/16 11:06:41 拓冰建站 浏览量
Leetcode 39 组合总和

题意理解:

        一个 无重复元素 的整数数组 candidates 和一个目标整数 target    

        从candidates 取数字,使其和== target ,有多少种组合(candidates 中的 同一个 数字可以 无限制重复被选取

        这道题和之前一道组合的区别:这道题允许重复的数字

解题思路

        组合问题——>递归

        这道题特殊的地方,对组合内数字的和做了要求,而不是个数,一开始并不确定树的深度,组合的大小是不定的。

1.暴力回溯+剪枝优化

class Solution {List<List<Integer>> result=new ArrayList<>();LinkedList<Integer> path=new LinkedList<>();int sum=0;public List<List<Integer>> combinationSum(int[] candidates, int target) {backtracking(candidates,target,0);return result;}public void backtracking(int[] candidates,int target,int index){//结果收集if(sum==target){result.add(new ArrayList<>(path));return;} else if (sum>target) {//剪枝return;}//遍历分支for(int i=index;i<candidates.length;i++){path.add(candidates[i]);sum+=candidates[i];//递归backtracking(candidates,target,i);//回溯path.removeLast();sum-=candidates[i];}}
}

2.分析

时间复杂度:O(n\times 2^{n})

        n个位置,每个位置有两种可能选或不选。

        时间复杂度和树的深度有关,是所有可行解之和

空间复杂度:O(n)