给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。
输入: n = 4, k = 2
输出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
回溯方法, 注意去重, 限制下一层搜索的起点.
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
results = []
def dfs(path, start):
if len(path) == k:
results.append(path[:])
for i in range(start, n + 1):
path.append(i)
dfs(path, i + 1)
path.pop()
dfs([], 1)
return results