39-组合总和

题目

给定一个无重复元素的数组 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]
]

题解

class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res=new ArrayList<>();
        List<Integer> path=new ArrayList<>();
        Arrays.sort(candidates);
        dfs(candidates,target,res,path,0);
        return res;
    }
    //参数:备选数组,目标数,结果集,过程集,深度
    private void dfs(int[] candidates,int target,List<List<Integer>> res,List<Integer> path,int start){
        if(target==0){
            res.add(new ArrayList<Integer>(path));//为什么一定要添加一个新的list呢?原来的path不就已经是一个arraylist了吗?
            return;
        }
        //从索引start开始遍历。结束条件有两个。一个是遍历到底时结束。另一个是剩余目标和大于当前数组值才遍历(剪枝)。这两个不能换位置,否则会索引溢出
        for(int i=start;i<candidates.length&&target>=candidates[i];i++){
            path.add(candidates[i]);
            dfs(candidates,target-candidates[i],res,path,i);
            //这层的数据处理完了,退回上一层
            path.remove(path.size()-1);//list的长度是size
        }
    }
}

思路:

  1. 回溯算法。

  2. 回溯法和动态规划的不同:动态规划只评估出一个最优解就行了,适合评估出一个方案。回溯法遍历出所有的方案,时间复杂度较高。

  3. 回溯算法中注意设置状态变量:depth表示递归到第几层。布尔数组used,false表示未选择,true表示已选择。

  4. 若排列问题讲究顺序的使用used数组。若组合问题讲究顺序的使用begin变量。

  5. 做法:
    1、先排序
    2、定义结果集。回溯路径集。作为参数传递到递归方法中。返回结果集
    3、递归方法:深度优先递归
    4、结束条件。目标和==0时结束。添加到结果集中
    5、否则遍历数组。从上一个递归遍历位置处开始遍历。同时结束条件还需要剪枝。剩余目标和大于当前数组值时结束。
    6、当前元素添加到回溯集。递归调用。更新剩余目标和。当前遍历索引传入。
    7、回溯
    时间复杂度:O(n*n),空间复杂度:O(target)。最坏的情况是元素1遍历target次,和为target

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

codrab

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值