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], ]
思路分析:还是考察DP,递推公式考察两种情况,前面n-1个整数组成长度为k-1的组合(包含当前整数)以及前面n-1个整数组成长度为k的组合(不含当前整数)
AC Code
public class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if(k > n || n == 0 || k == 0){
return res;
}
if(k == 1){
for(int i = 1; i <= n; i++){
List<Integer> sub = new ArrayList<Integer>();
sub.add(i);
res.add(sub);
}
} else {
List<List<Integer>> tmp1 = combine(n-1, k);
res.addAll(tmp1);
List<List<Integer>> tmp2 = combine(n-1, k-1);
for(List<Integer> tmp2Iterm : tmp2){
tmp2Iterm.add(n);
}
res.addAll(tmp2);
}
return res;
}
}