Combinations
Given two integers n and k, return all possible ombinations 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], ]
回溯法
复杂度
时间 O(N) 空间 O(K)
思路
通过深度优先搜索,回溯出所有可能性即可。
代码
public class Solution {List<List<Integer>> res = new ArrayList<List<Integer>>();public List<List<Integer>> combine(int n, int k) {dfs(1, k, n, new ArrayList<Integer>());return res;}private void dfs(int start, int k, int n, List<Integer> tmp){// 当已经选择足够数字时,将tmp加入结果if(k == 0){res.add(new ArrayList<Integer>(tmp));}// 每一种选择数字的可能for(int i = start; i <= n; i++){tmp.add(i);dfs(i + 1, k - 1, n, tmp);tmp.remove(tmp.size() - 1);}}
}
公式法
复杂度
时间 O(N) 空间 O(N)
思路
在数学中,组合数有这么一个性质
$$ C_{n}^{k}=C_{n-1}^{k-1}\cup n+C_{n-1}^{k}$$
所以,我们可以分别求出C(n-1,k-1)和C(n-1,k),并将前者都加上n,最后将两个结果和到一起,就是C(n,k)。而递归的Base条件是当n=0,k=0或者n<k时,返回一个空列表。
注意
当C(n-1,k-1)返回的是空列表时,要加一个空列表进去,否则for循环会被跳过
代码
public class Solution {public List<List<Integer>> combine(int n, int k) {// Recursion: C(n, k) = C(n-1, k-1) U n + C(n-1, k)// Base: C(0, k) C(n, 0) n < k ---> emptyList<List<Integer>> res = new LinkedList<List<Integer>>();if(n < k || n == 0 || k == 0){return res;}// C(n-1, k-1) U nList<List<Integer>> temp = combine(n-1, k-1);List<List<Integer>> part1 = new LinkedList<List<Integer>>();// 加入一个空列表,防止跳过for循环if(temp.isEmpty()){List<Integer> list = new LinkedList<Integer>();temp.add(list);}for(List<Integer> list : temp){list.add(n);part1.add(list);}// C(n-1, k)List<List<Integer>> part2 = combine(n-1, k);res.addAll(part1);res.addAll(part2);return res;}
}