Может кто-нибудь помочь, пожалуйста, почему вывод не правильный? Учитывая набор различных целых чисел, nums, возвращают все возможные подмножества (набор мощности).
class Solution(object):
sol =[]
index = 0
def subsets(self, nums):
sol = []
index = 0
curr = []
self.helper(nums, sol, index, curr)
return sol
def helper(self, nums, sol, index, curr = []):
if index == len(nums) or len(nums)== 0:
sol.append(list(curr))
return sol
self.helper(nums, sol, index +1, curr)
curr.append(nums[index])
self.helper(nums, sol, index + 1, curr)
s = Solution()
print (s.subsets([1, 2, 3]))
real output = [[], [3], [3, 2], [3, 2, 3], [3, 2, 3, 1], [3, 2, 3, 1, 3], [3, 2, 3, 1, 3, 2], [3, 2, 3, 1, 3, 2, 3]]
ожидаемый результат: [[], [1], [1,2], [1,2,3], [1,3], [2], [2,3] ], [3]]
Если я изменю curr на string (это был список ранее), тогда он работает и дает правильный результат:
class Solution(object):
sol =[]
index = 0
def subsets(self, nums):
sol = []
index = 0
curr = ""
self.helper(nums, sol, index, curr)
return sol
def helper(self, nums, sol, index, curr):
if index == len(nums) or len(nums)== 0:
print (curr, "===")
sol.append(list(curr))
return sol
self.helper(nums, sol, index +1, curr)
#append(nums[index])
curr = curr + str(nums[index])
self.helper(nums, sol, index +1, curr)
s = Solution()
print (s.subsets([1,2, 3]))