题目
Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
Example:
Input: n = 4, k = 2 Output: [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ]
思路
组合分两部分:
1、[1,n-1] 内的K个数
2、[1,n-1] 内的K-1个数 + n
def combine(self, n: int, k: int) -> List[List[int]]:
if n == 0 or k == 0:
return []
elif k == 1:
ans = []
for i in range(n):
ans.append([i+1])
return ans
ans = self.combine(n-1,k)
second = self.combine(n-1,k-1)
for item in second:
ans.append(item+[n])
return ans