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