問題文
return all possible combinations of k numbers chosen from the range [1, n].
Input: n = 4, k = 2
Output: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
コード
def combine(self, n: int, k: int):
ans = []
def backtrack(first, combination):
if len(combination) == k:
ans.append(combination[:]) # <- point
return
for i in range(first, n+1):
combination.append(i)
backtrack(i+1, combination)
combination.pop() # <- point
backtrack(1, [])
return ans