算法-回溯-组合总和2

算法-回溯-组合总和2

1 题目概述

1.1 题目出处

https://leetcode-cn.com/problems/combination-sum-ii/

1.2 题目描述

给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的每个数字在每个组合中只能使用一次。

说明:

所有数字(包括目标数)都是正整数。
解集不能包含重复的组合。
示例 1:

输入: candidates = [10,1,2,7,6,1,5], target = 8,
所求解集为:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]
示例 2:

输入: candidates = [2,5,2,1,2], target = 5,
所求解集为:
[
[1,2,2],
[5]
]

2 回溯法

2.1 思路

这段转自组合总和-解题思路

回溯法的解体框架是什么呢,解决一个回溯问题,实际上就是一个决策树的遍历过程。一般来说,我们需要解决三个问题:

  • 路径:也就是已经做出的选择。
  • 选择列表:也就是你当前可以做的选择。
  • 结束条件:也就是到达决策树底层,无法再做选择的条件。

其中最关键的点就是:在递归之前做选择,在递归之后撤销选择。

LinkedList result = new LinkedList();
public void backtrack(路径,选择列表){
    if(满足结束条件){
        result.add(结果);
    }
    for(选择:选择列表){
        做出选择;
        backtrack(路径,选择列表);
        撤销选择;
    }
}

所以我们这里只需要按套路来就行了,不过需要注意一些地方:

  • 要将数组提前排序,且结束条件写在for循环里,才能剪枝,否则会进行不必要递归
  • 遍历路径时,需要排除和该趟遍历里前一个数字相同的当前数字,否则会出现重复组合

2.2 代码

class Solution {
    private List<List<Integer>> resultList = new LinkedList<>();
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        if(null == candidates || candidates.length == 0){
            return resultList;
        }
        // 为了剪枝
        Arrays.sort(candidates);
        backtrack(candidates, target, 0, new LinkedList<Integer>(), 0);
        return resultList;
    }

    private void backtrack(int[] candidates, int target, int start, List<Integer> tmpList, int tmpSum){
        // 克隆一个list避免递归之间互相影响
        LinkedList<Integer> newList = new LinkedList<>(tmpList);
        for(int i = start; i < candidates.length; i++){
            if(i > start && candidates[i] == candidates[i-1]){
                // 该次遍历已经在相同位置用过该相同数字,跳过
                continue;
            }
            // 选择当前
            int tmpSum2 = tmpSum + candidates[i];
            if(tmpSum2 > target){
                // 剪枝1
                break;
            }
            newList.add(candidates[i]);
            if(tmpSum2 == target){
                // 剪枝2
                resultList.add(new LinkedList<Integer>(newList));
                break;
            }
            // 否则还需要继续加下一个数
            backtrack(candidates, target, i + 1, newList, tmpSum2);
            // 不选当前
            newList.removeLast();
        }
    }
}

2.3 时间复杂度

在这里插入图片描述
时间复杂度和元素个数、大小、target大小密切相关

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值