1 Star 0 Fork 0

ZechariahZheng / blog文档

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
回溯算法+剪枝.md 5.86 KB
一键复制 编辑 原始数据 按行查看 历史
ZechariahZheng 提交于 2019-11-28 09:49 . blog文档

题目:LeetCode39 https://leetcode-cn.com/problems/combination-sum/

解题思路:

做搜索、回溯问题的套路是画图,代码其实就是根据画出的树形图写出来的。

那么如何画图呢?

根据题目中的用例,画一个图,因为是搜索,因此呈现的是一个树形结构图,并且在这个树形结构中会体现出递归结构。 根据题目中的用例,比对自己画图的结果和题目的结果的差异,如果一样,说明我们的分析没有错;如果不一样,说明我们的分析有误,一定有哪一个环节漏掉了或者分析错误,根据找到的问题调整算法。 下面我具体说一下,本来想展示草稿的,奈何本人画的图太难看,还是用软件画图给大家看吧。

针对示例 1:

输入: candidates = [2, 3, 6, 7],target = 7,所求解集为: [[7], [2, 2, 3]]

画的图是这样的:

思路:以 target = 7 为根结点,每一个分支做减法。减到 00 或者负数的时候,剪枝。其中,减到 00 的时候结算,这里 “结算” 的意思是添加到结果集。

39-1.png

文字的部分去掉了,这样大家看得清楚一点:

39-2.png

说明:

1、一个蓝色正方形表示的是 “尝试将这个数到数组 candidates 中找组合”,那么怎么找呢?挨个减掉那些数就可以了。

2、在减的过程中,会得到 00 和负数,也就是被我标红色和粉色的结点:

得到 00 是我们喜欢的,从 00 这一点向根结点走的路径(很可能只走过一条边,也算一个路径),就是一个组合,在这一点要做一次结算(把根结点到 00 所经过的路径,加入结果集)。

得到负数就说明这条路走不通,没有必要再走下去了。

总结一下:在减的过程中,得到 00 或者负数,就没有必要再走下去,所以这两种情况就分别表示成为叶子结点。此时递归结束,然后要发生回溯。

画出图以后,我看了一下,我这张图画出的结果有 44个 00,对应的路径是 [[2, 2, 3], [2, 3, 2], [3, 2, 2], [7]],而示例中的解集只有 [[7], [2, 2, 3]],很显然,我的分析出现了问题。问题是很显然的,我的结果集出现了重复。重复的原因是

后面分支的更深层的边出现了前面分支低层的边的值。

但是这个问题也不难解决,把候选数组排个序就好了(想一下,结果数组排个序是不是也可以去重),后面选取的数不能比前面选的数还要小,即 “更深层的边上的数值不能比它上层的边上的数值小”,按照这种策略,剪枝就可以去掉重复的组合。

39-3.png

from typing import List


class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        size = len(candidates)
        if size == 0:
            return []

        # 剪枝的前提是数组元素排序
        # 深度深的边不能比深度浅的边还小
        # 要排序的理由:1、前面用过的数后面不能再用;2、下一层边上的数不能小于上一层边上的数。
        candidates.sort()
        # 在遍历的过程中记录路径,一般而言它是一个栈
        path = []
        res = []
        # 注意要传入 size ,在 range 中, size 取不到
        self.__dfs(candidates, 0, size, path, res, target)
        return res

    def __dfs(self, candidates, begin, size, path, res, target):
        # 先写递归终止的情况
        if target == 0:
            # Python 中可变对象是引用传递,因此需要将当前 path 里的值拷贝出来
            # 或者使用 path.copy()
            res.append(path[:])

        for index in range(begin, size):
            residue = target - candidates[index]
            # “剪枝”操作,不必递归到下一层,并且后面的分支也不必执行
            if residue < 0:
                break
            path.append(candidates[index])
            # 因为下一层不能比上一层还小,起始索引还从 index 开始
            self.__dfs(candidates, index, size, path, res, residue)
            path.pop()


if __name__ == '__main__':
    candidates = [2, 3, 6, 7]
    target = 7
    solution = Solution()
    result = solution.combinationSum(candidates, target)
    print(result)
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;

public class Solution {

    private List<List<Integer>> res = new ArrayList<>();
    private int[] candidates;
    private int len;

    private void findCombinationSum(int residue, int start, Stack<Integer> pre) {
        if (residue < 0) {
            return;
        }
        if (residue == 0) {
            res.add(new ArrayList<>(pre));
            return;
        }
        for (int i = start; i < len; i++) {
            pre.add(candidates[i]);
            findCombinationSum(residue - candidates[i], i, pre);
            pre.pop();
        }
    }

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        int len = candidates.length;
        if (len == 0) {
            return res;
        }
        this.len = len;
        this.candidates = candidates;
        findCombinationSum(target, 0, new Stack<>());
        return res;
    }

    public static void main(String[] args) {
        int[] candidates = {2, 3, 6, 7};
        int target = 7;
        Solution3 solution = new Solution3();
        List<List<Integer>> combinationSum = solution.combinationSum(candidates, target);
        System.out.println(combinationSum);
    }
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/ZechariahZheng/blog_document.git
git@gitee.com:ZechariahZheng/blog_document.git
ZechariahZheng
blog_document
blog文档
master

搜索帮助

344bd9b3 5694891 D2dac590 5694891