【发布时间】:2019-06-07 02:34:24
【问题描述】:
我正在尝试打印总和为给定目标数的所有可能子数组。
# arr -- the array
# n -- length of the array
# target_sum -- sum we want
# target_arr -- subarray we test for having the right sum
# ite -- iterator
def subset_sum(arr,n,target_sum,target_arr=[],ite=0):
for i in range(ite,n):
target_arr.append(arr[i])
if sum(target_arr)==target_sum:
print (target_arr, len(target_arr))
target_arr.pop()
subset_sum(arr,n,target_sum,target_arr,ite+1)
return
subset_sum(arr,n,target_sum,target_arr,i+1)
target_arr.pop()
subset_sum([1,2,3,4],4,4)
[1, 3] 2
[1, 3] 2
[4] 1
[4] 1
[4] 1
[4] 1.
我似乎能够打印所有子数组,但我不知道为什么我的代码让我打印重复项。我认为可以避免重复,因为我在最后弹出子数组(即回溯)。
我的代码在哪里导致重复?我试过了,但不知道为什么。
【问题讨论】:
-
这是什么语言?
-
这是在 Python 中。
标签: python recursion recursive-backtracking