题目:
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], ]解法:
题目要求输出1~n的所有含k个元素组合,很容易想到利用递归的思路,将问题分解为更小的子问题。
1~n的组合可以分为含有n,和不含有n,即(n-1,k-1)的集合中加上n,以及(n-1,k)的集合,将两部分合并即为结果
import java.util.ArrayList;
import java.util.List;
public class No77_Combinations {
public static void main(String[] args){
System.out.println(combine(4, 2));
}
public static List<List<Integer>> combine(int n, int k) {
List<List<Integer>> ret = new ArrayList<List<Integer>>();
if(n < 1 || n < k) return ret;
if(k == 0) return ret;
if(k == n) {
List<Integer> element = new ArrayList<Integer>();
for(int i=1;i<=n;i++)
element.add(i);
ret.add(element);
return ret;
}
List<List<Integer>> withN = combine(n-1, k-1);
if(withN.size() == 0){
List<Integer> element = new ArrayList<Integer>();
element.add(n);
ret.add(element);
}
for(int i=0;i<withN.size();i++){
withN.get(i).add(n);
ret.add(withN.get(i));
}
List<List<Integer>> withoutN = combine(n-1, k);
for(int i=0;i<withoutN.size();i++){
ret.add(withoutN.get(i));
}
return ret;
}
}