给定两个整数 n
和 k
,返回范围 [1, n]
中所有可能的 k
个数的组合。
你可以按 任何顺序 返回答案。
python:剪枝
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
ans = [] # stone the answer
self.backtracking(n,k,1,[],ans)
return ans
def backtracking(self, n: int, k: int, startIndex:int, path:list,ans:list):
# stop condition: the length of path is equal to k
if len(path) == k:
ans.append(path[:])
return
# Node process
for i in range(startIndex, n+len(path)-k+1+1):
path.append(i) # Node process
self.backtracking(n,k,i+1,path,ans)
path.pop() # Backtrack, undo processed nodes