给出两个整数n和k,返回从1到n中取k个数字的所有可能的组合
例如:
如果n=4,k=2,结果为
[ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ]
## 二叉树思路,yes or no,是否添加当前index数据 ## 递归添加当前路径 def binaryTreeSeq(nums,k,index,path,ans): if len(path)==k: ans.append(path) return if index==len(nums):return no=path binaryTreeSeq(nums,k,index+1,no,ans) yes=path+[nums[index]] binaryTreeSeq(nums,k,index+1,yes,ans) class Solution: def combine(self , n , k ): nums = list(range(1, n+1)) ans=[] binaryTreeSeq(nums,k,0,[],ans) ans=ans[::-1] return(ans) # write code here