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], ]
这题目实现需要点小技巧,以前在ACM题中见过。
public ArrayList<ArrayList<Integer>> combine(int n, int k) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
if (k <= 0) {
return result;
}
int[] kAarray = new int[k];
int i = 0;
kAarray[0] = 0;
while (i >= 0) {
kAarray[i]++;
if (kAarray[i] > n) {
kAarray[i] = 0;
i--;
} else {
if (i == k - 1) {
ArrayList<Integer> list = new ArrayList<Integer>(k);
for (int kk : kAarray) {
list.add(kk);
}
result.add(list);
} else {
kAarray[i+1] = kAarray[i];
i++;
}
}
}
return result;
}