给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。
示例:
输入: n = 4, k = 2
输出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
DFS:
class Solution(object):
def combine(self, n, k):
"""
:type n: int
:type k: int
:rtype: List[List[int]]
"""
res = []
self.dfs(range(1,n+1),k,res,[])
return res
def dfs(self,nums,k,res,path):
if k > len(nums):
return
#终止条件
elif k == 0:
res.append(path)
else:
for i in range(len(nums)):
self.dfs(nums[i+1:],k-1,res,path+[nums[i]])
调包:pythonic解法
class Solution(object):
import itertools
def combine(self, n, k):
"""
:type n: int
:type k: int
:rtype: List[List[int]]
"""
return list(itertools.combinations(range(1,n+1),k))