【发布时间】:2020-03-20 06:37:51
【问题描述】:
我得到了一个整数数组 A,我需要返回一个包含它所有子集的数组。 我已经尝试使用回溯来解决这个问题。
def subset_helper(index, result, A, temp):
result.append(temp)
#print(temp)
for i in range(index,len(A)):
temp.append(A[i])
subset_helper(i+1,result,A,temp)
#backtracking
temp.pop()
return
def subsets(A):
result = []
temp = []
index = 0
subset_helper(index, result, A, temp)
return result
这会返回一个空列表。打印 temp 给了我正确的答案,但问题要求我返回一个数组。我猜由于 按引用调用 导致的临时数组在每次迭代中都会发生变化,这可能是它给我一个空列表列表的原因。
Input : [12,13]
Expected Output : [[],[12],[12,13],[13]]
My Output : [[],[],[],[]]
【问题讨论】:
标签: python pass-by-reference backtracking