老师请问您以下问题应如何求解:
Determine if there exists three elements in a given array that sum to the given target number. Return all the triple of values that sums to target.
Assumptions
- The given array is not null and has length of at least 3
- No duplicate triples should be returned, order of the values in the tuple does not matter
Examples
*A = [3, 4, 0, -1, 2, 0, 5], target = 4,return [[-1, 0, 5], [-1, 2, 3], [0, 0, 4]]
==============================================================
以下是我写的code,但是返回的时候显示的是[[-1, 0, 5], [-1, 0, 5], [-1, 2, 3], [0, 0, 4]] 请老师帮助解答,十分感谢。
def allTriples(array, target):
array = combination_n(array,3)
lst = list(array)
a = []
for i in lst:
if sum(i) == target and i not in a:
a.append(i)
return a
def combination_n(array,n):
if n == 0:
return [[]]
res = []
for i in range(0,len(array)):
m = array[i]
remlist = array[i+1:]
for p in combination_n(remlist,n-1):
res.append([m]+p)
return res
array = [3, 4, 0, -1, 2, 0, 5]
target = 4
result = allTriples(array,target)
print(result)