题目来自leetcode.com
Given an array nums
of n integers and an integer target
, are there elements a, b, c, and d in nums
such that a + b + c + d = target
? Find all unique quadruplets in the array which gives the sum of target
.
class Sol():
def __init__(self, a1=0,a2=0,a3=0,a4=0):
self.a1 = a1
self.a2 = a2
self.a3 = a3
self.a4 = a4
def update(self,a1,a2,a3,a4):
self.a1 = a1
self.a2 = a2
self.a3 = a3
self.a4 = a4
def _num(a1,a2,a3,a4,arr,target):
sum = arr[a1]+arr[a2]+arr[a3]+arr[a4]
if sum == target:
return True
else:
return False
def printt(ans):
print('['+str(arr[ans.a1])+','+str(arr[ans.a2])+','+str(arr[ans.a3])+','+str(arr[ans.a4])+']')
ans = []
target = input("input the target num ")
num = input("input the number of array ")
target = int(target)
num = int(num)
arr = []
a = 0
while a < num:
arr.append(int(input()))
a += 1
a = 0
while a < num-3:
b = a+1
while b <num-2:
c = b+1
while c <num-1:
d = c+1
while d <num:
e = _num(a,b,c,d,arr,target)
if e:
ans.append(Sol(a,b,c,d))
d += 1
c += 1
b += 1
a += 1
for an in ans:
printt(an)