Subsets, Combination, Permutation, Combination Sum

来源:互联网 发布:餐饮收银软件多少钱 编辑:程序博客网 时间:2024/06/05 05:00

1. Combination 类问题最重要的是去重, dfs() 函数里带一个 index 参数可以很好的解决这个问题。

2. dfs里增加一个“前一个元素”的参数,每一层递归只考虑比上一个元素大的值。

public class Solution {
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        helper(res, new ArrayList<Integer>(), n, k, 1);
        return res;
    }
    
    private void helper(List<List<Integer>> res, List<Integer> tem, int n, int k, int pos){
        if(tem.size() == k) {
            res.add(new ArrayList<Integer>(tem));
        }
        else{
            for(int i = pos; i <= n; i++){
                tem.add(i);
                helper(res, tem, n, k, i+1);
                tem.remove(tem.size()-1);
            }
        }
    }
}

LintCode - Combination Sum

1. 因为同一个数可以用多次,新一层 dfs 迭代的时候要从上一层一样的 index 开始。
2. 同时因为同一个元素可以用多次,必须要有一个有效的 dfs 终止条件,不然搜索树会永远一直加下去。condition: sum> target
public class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        if(candidates == null || candidates.length == 0){
            return new ArrayList<List<Integer>>();
        }
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        helper(res, new ArrayList<Integer>(), target, candidates, 0);
        return res;
    }
    
    private void helper(List<List<Integer>> res, List<Integer> tem, int target, int[] candidates, int pos){
        if(target == 0){
            res.add(new ArrayList<Integer>(tem));
            return;
        }
        if(target < 0){
            return;
        }
        for (int i = pos; i < candidates.length; i++){
            tem.add(candidates[i]);
            helper(res, tem, target-candidates[i], candidates, i);  
            tem.remove(tem.size()-1);
        }
    }
}

LintCode - Subsets

因为是distinct,每加一个新元素直接加到list中就好啦

LintCode - Permutations

1. 这次每轮dfs都考虑所有元素,因此不用再传index了。

2. 建一个used数组,挑过的数做个标记。下次直接跳过。


0 0