生成数组的所有子集

2024-10-01 19:30:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在生成数组的所有可能的子集。我正在研究一个递归解决方案,其中我维护一个索引,我在每一步递增。在递增索引之后,我弹出最后一个元素。我不明白为什么数组中的最后一个元素会重复。在

class Solution(object):
  def subsets(self, nums):
    """
    :type nums: List[int]
    :rtype: List[List[int]]
    """
    # You need to keep track of a list of all the subarrays, the current subarray, the index and the original array
    return self.helper(nums, 0, [], [])


  def helper(self, nums, index, fullSol, curr):
    fullSol.append(list(curr)) # add this current array to the list of all subarrays
    print(fullSol)

    # Iterate through the indices
    for i in range(index, len(nums)): 
        curr.append(nums[index]) # add the next element to the current list
        self.helper(nums, i+1, fullSol, curr) # increment the index
        curr = curr[:-1] # remove the last element from the current subarray

Tags: ofthetoselfhelper元素indexdef

热门问题