题目链接:https://leetcode.com/problems/combinations/
题目:
n and k, return all possible combinations of k numbers out of 1 ... n.
For example,
If n = 4 and k
[ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ]
思路:
经典组合问题。
算法:
int k = 0;
List<List<Integer>> iLists = new ArrayList<List<Integer>>();
List<Integer> list = new ArrayList<Integer>();
int n = 0;
public List<List<Integer>> combine(int n, int k) {
this.n = n;
this.k = k;
dspComb(0);
return iLists;
}
void dspComb(int cur) {
if (list.size() == k) {
iLists.add(new ArrayList<Integer>(list));
} else {
for (int i = cur; i < n; i++) {
list.add(i + 1);
dspComb(i + 1);
list.remove(list.size() - 1);
}
}
}