解题思路
回溯算法
python 代码
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
trace = []
ret = []
self.backtrace(n,k,1,trace,ret)
return ret
def backtrace(self,n,k,start,trace,ret):
if len(trace)==k:
ret.append(trace[:])
return
for i in range(start,n+1):
trace.append(i)
self.backtrace(n,k,i+1,trace,ret)
trace.pop()
s = Solution()
result = s.combine(4,2)
print(result)