-1

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.

Eventually I want to return a list of lists

I thought on starting from the end, using some kind of DP. None of the things I've tried got even close to it

Thank you

Eize
  • 11
  • 3
  • This question is missing context or other details: Please improve the question by providing additional context, which ideally includes your thoughts on the problem and any attempts you have made to solve it. This information helps others identify where you have difficulties and helps them write answers appropriate to your experience level. You also need to state exactly what the problem is, your attempted code, what you expected, what you got, and any traceback. – Rory Daulton Dec 09 '18 at 23:47
  • Go through this link , for the solution using Recursion https://stackoverflow.com/a/71042729/14286781 – S Nagendra Feb 09 '22 at 00:57

1 Answers1

1

Handling the last element (n-1) first allows you to not pass intermediate results with the given function signature:

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]]
user2390182
  • 72,016
  • 6
  • 67
  • 89