美文网首页
Leetcode BackTracking问题汇总

Leetcode BackTracking问题汇总

作者: 尴尴尬尬先生 | 来源:发表于2017-06-06 11:35 被阅读0次
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 BackTracking问题汇总

      本文链接:https://www.haomeiwen.com/subject/gyygfxtx.html