77 Combinations
https://leetcode.com/problems/combinations/#/description
Given two integersnandk, return all possible combinations ofknumbers out of 1 ...n.
For example,
Ifn= 4 andk= 2, a solution is:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
分析及代码
……被之前题目卡住了,非常无耻地水了这题算人头
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> res = new ArrayList<>();
generate(res, new ArrayList<>(), n, k, 1);
return res;
}
private void generate(List<List<Integer>> res, List<Integer> item, int n, int k, int index) {
if(item.size() == k) {
res.add(new ArrayList<>(item));
return;
}
for(int i = index; i <= n; i++) {
item.add(i);
generate(res, item, n, k, i + 1);
item.remove(item.size() - 1);
}
}