class Solution: def combine(self, n: int, k: int): nums=[x+1 for x in range(n)] res,ans=[],[] def dfs(nums:list[int]): if len(ans)==k: ans_copy=ans.copy()#复制,避免ans数组改变使res跟着改变 res.append(ans_copy) return for c,i in enumerate(nums[:n-(k-len(ans))+1]): ans.append(i) dfs(nums[c+1:]) ans.pop() dfs(nums) return res try: solution=Solution() res=solution.combine(4,2) print(res) solution=Solution() res=solution.combine(4,3) print(res) except: print('error')
标签:剪枝,nums,int,res,solution,dfs,77,ans From: https://www.cnblogs.com/tanyuanqing/p/17660027.html