给定两个整数
n
和
k
,返回 1 …
n
中所有可能的
k
个数的组合。
示例:
输入: n = 4, k = 2 输出: [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ]
class Solution:
def com(self,result,res,n,k,w):
if len(res)==k:
result.append(res.copy())
return
for i in range(w,n+1):#遍历从1开始到n结束
res.append(i)
self.com(result,res,n,k,i+1)
del res[-1]
def combine(self, n, k):
"""
:type n: int
:type k: int
:rtype: List[List[int]]
"""
#典型的递归问题
result=[]
res=[]
self.com(result,res,n,k,1)
return result
执行用时: 660 ms, 在Combinations的Python3提交中击败了60.34% 的用户
版权声明:本文为weixin_42234472原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。