好像自从上次 CSDN Blog 系统故障后,博文阅读量过百后系统不再发放C币,尽管我也不知道C币有啥用。
(Updated on 2014/12/10) 原来规则是阅读量没超过300送一个C币,C币可以用来换奖品,但一般好像要博客、论坛等多个地方的C币一起用:-(
【题目】
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], ]
题意:求 C(n, k) 的所有组合。
【组合生成算法】【回溯】
public class Solution {
List<List<Integer>> ans = new ArrayList<List<Integer>>();
int n = 0;
int k = 0;
public List<List<Integer>> combine(int n, int k) {
this.n = n;
this.k = k;
List<Integer> list = new ArrayList<Integer>();
backTracking(list, 1);
return ans;
}
public void backTracking(List<Integer> list, int from) {
if (list.size() == k) {
List<Integer> newList = new ArrayList<Integer>(list);
ans.add(newList);
return;
}
for (int i = from; i <= n; i++) {
list.add(i);
backTracking(list, i + 1);
list.remove(new Integer(i));
}
}
}