0.原题:
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.代码
class Solution:
def my_init(self,n,k):
self.n = n
self.k = k
self.temp_result = [-1 for _ in range(k)]
self.result = []
self.visited = [False for _ in range(n)]
def combine(self, n, k):
"""
:type n: int
:type k: int
:rtype: List[List[int]]
"""
self.my_init(n,k)
self.fun(0,0)
return self.result
def fun(self,start,index):
if index == self.k:
r = self.temp_result.copy()
self.result.append(r)
return 0
else:
for i in range(start,self.n):
self.temp_result[index] = i + 1
self.fun(i+1,index+1)
return 0