77. Combinations

1次阅读

共计 695 个字符,预计需要花费 2 分钟才能阅读完成。

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();
}
}
}

正文完
 0