python关于递归求组合与组合数:
- 首先需要找到递归的突破口。
- 要求如下:
Exercise 3: Enumerating Combinations
You need to write a function, comb(n, k), that returns a list consisting of all the combinations of 𝑘 elements out of a set {1,2,…,𝑛} . Your implementation should be using recursions instead of for loop (you may use list comprehension though).
如果初学python建议用库函数解决, 那还学什么递归算法。用iteration库函数解决的可以不看下面内容。
如果求组合数, 可以用以下公式:
def comb(n, k): # the number of combinations
if k > n:
return 0
elif k == 1:
return n
elif n == 1:
return k # k is 1 or 0
else:
return comb(n - 1, k - 1) + comb(n - 1, k)
comb(6, 3)
20
如果理解以上递归, 可以用以上的递归列出所有的组合:
把以上的函数转化为列表:
def comb(n, k):
if k == n:
return [[i for i in range(1, n