Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
Example:
Input: n = 4, k = 2
Output:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
难度:medium
题目:给定整数n 和k, 返回1到n 中k个数的所有组合。
思路:递归+剪枝
Runtime: 4 ms, faster than 93.58% of Java online submissions for Combinations.
Memory Usage: 43.1 MB, less than 1.39% of Java online submissions for Combinations.
class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> result = new ArrayList<>();
combine(n, 1, k, new Stack<>(), result);
return result;
}
private void combine(int n, int begin, int k, Stack<Integer> stack, List<List<Integer>> result) {
if (k <= 0) {
result.add(new ArrayList<>(stack));
return;
}
for (int i = begin; i <= n - k + 1; i++) {
stack.push(i);
combine(n, i + 1, k - 1, stack, result);
stack.pop();
}
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。