Leetcode BackTracking问题汇总

public class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        List<List<Integer>> result = new LinkedList<>();
        helper(result, new LinkedList<>(), candidates, target, 0);
        return result;
    }
    private static void helper(List<List<Integer>> result, List<Integer> cur, int[] candidates, int target,int start) {
        if(target>0){
            for(int i = start;i<candidates.length&&target-candidates[i]>=0;i++){
                cur.add(candidates[i]);
                helper(result, cur, candidates, target-candidates[i], i);
                cur.remove(cur.size()-1); // 关键的回退一步,要回到选择前的状态
            }
        }
        else if(target==0){
            result.add(new LinkedList<>(cur));

        }
    }
}

这类问题的大概思路都是寻找一条正确的路,当遇到岔口时,先尝试一条路,走不通就依次返回上一个岔路,要注意回到岔路时要重置状态。

cur.remove(cur.size()-1); // 关键的回退一步,要回到选择前的状态

就是这一句的意义。
当有要求是不能重复的时候,要设置flag,或者设置boolean[],检查是否被用过。
参考文章:https://segmentfault.com/a/1190000006121957
参考文章:https://siddontang.gitbooks.io/leetcode-solution/content/backtracking/permutation.html

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,771评论 0 33
  • LeetCode 刷题随手记 - 第一部分 前 256 题(非会员),仅算法题,的吐槽 https://leetc...
    蕾娜漢默阅读 17,933评论 2 36
  • 作为一个前端程序猿,下面这些站会让你眼前一亮。 amazeui框架组建丰富 http://amazeui.org...
    欧巴冰冰阅读 8,919评论 18 303
  • 实话实说—探索中国生态之路! 中国环保路线错,都为环保来献策; 环保理论西洋派,中国处处闹灾害; 污水都往河里排,...
    科学新说阅读 892评论 0 0
  • 蝴蝶花盛开的那年,沈初见一个人蹲在河边看水里的鱼游来游去。小时候的沈初见是一个较为木讷的孩子,所以同...
    桑树非榆阅读 501评论 0 1