简体   繁体   English

使用递归查找所有k个子集

[英]finding all k subsets using recursion

I'm trying to find a way to make a recursive algorithm that will give all the k-length subsets of a set of numbers (0 -> n), but I cannot send a list to the function as an argument. 我正在尝试找到一种方法来制定递归算法,该算法将给出一组数字(0-> n)的所有k长度子集,但是我无法将列表作为参数发送给函数。

Eventually I want to return a list of lists 最终我想返回一个列表列表

I thought on starting from the end, using some kind of DP. 我想从头开始,使用某种DP。 None of the things I've tried got even close to it 我尝试过的所有事情都没有接近

Thank you 谢谢

Handling the last element ( n-1 ) first allows you to not pass intermediate results with the given function signature: 首先处理最后一个元素( n-1 )可以使您不传递具有给定函数签名的中间结果:

def subsets(n, k):
    if n < k or k < 0:
        return []
    if k == n:
        return [list(range(k))]
    return subsets(n-1, k) + [s+[n-1] for s in subsets(n-1, k-1)]

>>> subsets(3, 2)
[[0, 1], [0, 2], [1, 2]]
>>> subsets(4, 2)
[[0, 1], [0, 2], [1, 2], [0, 3], [1, 3], [2, 3]]
>>> subsets(4, 3)
[[0, 1, 2], [0, 1, 3], [0, 2, 3], [1, 2, 3]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM