题目描述:
Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
For example,
If n = 4 and k = 2, a solution is:
[ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ]
我的思路:
组合问题,给出两个整数n和k,返回所有可能的1~n中挑出k个数的组合。总数就是Cnk个。
我的代码:
class Solution:
def combine(self, n, k):
res = []
if k < 1: return res
for i in range(1, n-k+2):
self.helper(n, k, [i], res)
return res
def helper(self, n, k, curr, res):
if len(curr) == k:
res.append(curr)
else:
last = curr[-1]
for next in range(last+1, n+1):
self.helper(n, k, curr + [next], res)
Discuss:
class Solution:
def combine(self, n, k):
combs = [[]]
for _ in range(k):
combs = [[i] + c for c in combs for i in range(1, c[0] if c else n+1)]
return combs
学到:
如果想用递归解决问题,原函数的参数不够,可以直接重写原函数。