77. Combinations
Problem
Return every combination of k distinct numbers chosen from 1…n, in any order.
Example: n = 4, k = 2 → [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
Choose k of 1..n. Prune: only start values that leave enough numbers to finish (i ≤ n − (k − len(path)) + 1).
Complexity: O(k · C(n, k)).
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
res, path = [], []
def bt(start):
if len(path) == k:
res.append(path[:])
return
for i in range(start, n - (k - len(path)) + 2):
path.append(i)
bt(i + 1)
path.pop()
bt(1)
return res
assert sorted(map(sorted, Solution().combine(4, 2))) == sorted(map(sorted, [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]))
assert sorted(map(sorted, Solution().combine(1, 1))) == sorted(map(sorted, [[1]]))
class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> res = new ArrayList<>();
bt(n, k, 1, new ArrayList<>(), res);
return res;
}
private void bt(int n, int k, int start, List<Integer> path, List<List<Integer>> res) {
if (path.size() == k) { res.add(new ArrayList<>(path)); return; }
for (int i = start; i <= n - (k - path.size()) + 1; i++) {
path.add(i);
bt(n, k, i + 1, path, res);
path.remove(path.size() - 1);
}
}
}
func combine(n int, k int) [][]int {
res, path := [][]int{}, []int{}
var bt func(start int)
bt = func(start int) {
if len(path) == k {
res = append(res, append([]int{}, path...))
return
}
for i := start; i <= n-(k-len(path))+1; i++ { // leave room for the remaining picks
path = append(path, i)
bt(i + 1)
path = path[:len(path)-1]
}
}
bt(1)
return res
}