Search code examples
pythonrecursioncombinationsbacktracking

How do I return Combinations using recursion in Python


I want to print the combinations of all the elements of a list. But every time my codes results in a list of empty lists. What is want is input = [1,2,3] Output = [[3],[1],[2],[1,2,3],[1,3],[2,3],[1,2],[]] What I am getting is [[][][][][][][][]]

My Python code

class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
    result = []
    curNums = []
    def dfs(nums , i):
        if i == len(nums):
            result.append(curNums)
        else:
            curNums.append(nums[i])
            dfs(nums , i+1)
            curNums.pop()
            dfs(nums , i+1)
    dfs(nums , 0)
    return result

Solution

  • The curNums list you are appending is the same list every time - so the append/pop are all being made on the same list.

    Instead what you need to append to the result should be a new copy of the list every time - try result.append(curNums[:]). Creating a copy of the current list values.