美文网首页
LeetCode 77 Combinations

LeetCode 77 Combinations

作者: ShuiLocked | 来源:发表于2016-08-14 17:19 被阅读687次

LeetCode 77 Combinations

Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
For example,If n = 4 and k = 2, a solution is:
[ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4]]

对于permutation和combination这类题,都可以使用backtracing递归或是dp。

思路一:backtracing
一开始的naive thinking是,传递一个boolean数组记录当前有哪些数已经考虑过,然后每次调用dfs时将k-1。传递整个boolean空间会消耗过多的空间,不妨只传递一个pointer,在pointer之前的数所产生的combination都已经考虑过。

代码时注意两点:
1)java中是指针赋值,因此如果要深度copy某个list(eg. ArrayList<Integer> comb),需要采用如下方式:

ArrayList<Integer> newComb = new ArrayList(comb);

2)对于每个回溯,若combination还需要挑选k个数:
可以从start到n挑选k个
可以从start+1到n挑选k个
...
直到从n+1-k到n挑选k个(此时只有1种挑法)
再往后是不存在挑k个数的combination的,因此该条件可以作为backtracing的剪枝条件。

public class Solution {
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> combs = new ArrayList<>();
        if (k <= 0 || k > n) return combs;
        combs = combineRecursive(n, k, 1, new ArrayList<>(), combs);
        return combs;
    }
    
    public List<List<Integer>> combineRecursive(int n, int k, int start, List<Integer> comb, List<List<Integer>> combs) {
        if (k == 0) {
            combs.add(new ArrayList(comb));
            return combs;
        }
        
        for (int i = start; i <= n+1-k; i++) {
            comb.add(i);
            combs = combineRecursive(n, k-1, i+1, comb, combs);
            comb.remove(comb.size()-1);
        }
        return combs;
    }
    
}

思路二:dp
dp问题关键是找到递推公式,对于combination存在如下递推关系:

C(n,k) = C(n-1,k) + C(n-1,k-1)

即不取n的情况(此时还剩k个数要取)和取n的情况(此时还剩k-1个数要取)。
从n=0,k=0的情况赋初值。

代码如下:

public class Solution {
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>>[][] combs = new ArrayList[n+1][k+1];
        
        for (int i = 0; i <= n; i++) {
            combs[i][0] = new ArrayList<>();
            combs[i][0].add(new ArrayList<>());
        }
        
        for (int j = 1; j <= k; j++) {
            for (int i = j; i <= n-k+j; i++) {
                combs[i][j] = new ArrayList<>();
                
                if (i-j > 0) {
                    combs[i][j].addAll(combs[i-1][j]);
                }
                
                for (List tmp : combs[i-1][j-1]) {
                    List<Integer> tmpList = new ArrayList(tmp);
                    tmpList.add(i);
                    combs[i][j].add(tmpList);
                }
                 
            }
        }
        
        return combs[n][k];
    }
    
}

参考:
https://discuss.leetcode.com/topic/11718/backtracking-solution-java/8

相关文章

网友评论

      本文标题:LeetCode 77 Combinations

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