题目:
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], ]
思路:
Recursion, Code1 是我写的Run Time 时间比较长,估计是因为 传递 ArrayList 的缘故
Code1:
ArrayList<List<Integer>> al=new ArrayList<List<Integer>>();
ArrayList<Integer> line;
public List<List<Integer>> combine(int n, int k) {
line = new ArrayList<Integer>();
recurComb(line, 1, n, k);
return al;
}
public void recurComb(ArrayList<Integer> lastList, int start, int n, int k){
if(k==0){
al.add(lastList);
return;
}
for(int i=start;i<=n;i++){
line=new ArrayList<Integer>(lastList);
line.add(i);
recurComb(line, i+1, n, k-1);
}
}
Code2:
public List<List<Integer>> combine(int n, int k) {
return combine(1, n + 1, k);
}
public List<List<Integer>> combine(int low, int upper, int k) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (k == 1) {
for (int i = low; i < upper; i++) {
List<Integer> r = new ArrayList<Integer>();
r.add(i);
result.add(r);
}
return result;
}
for (int i = low; i < upper; i++) {
List<List<Integer>> r = combine(i + 1, upper, k - 1);
for (List<Integer> a : r) {
a.add(0, i);
}
result.addAll(r);
}
return result;
}
备注:
ArrayList 的赋值方式:
直接传递指针:
ArrayList a = new ArrayList();
ArrayList b = new ArrayList();
b= a;
传递内容:
ArrayList<Integer> b= new ArrayList<Integer>(a);
ArrayList<Integer> b =(ArrayList<Integer>) a.clone();
b.addAll( a )
For 的枚举用法:
int[] integers = { 1, 2, 3, 4 };
for (int i : integers) {
<span style="white-space:pre"> </span>System.out.println(i);
}