Target Sum
Question
Given an array of integers and a target number, find all possible combinations of integers that add up to the target number.
Example 1
None
Solution
- ▭
- ▯
all//Target Sum.py
def targetSum(arr, target):
if not arr or target is None:
return -1
result = []
for i in range(len(arr)):
for j in range(i+1, len(arr)):
if arr[i] + arr[j] == target:
result.append((arr[i], arr[j]))
return result
arr = [1, 2, 3, 4, 5]
target = 7
print(targetSum(arr, target)) # [(2,5), (3,4)]
all//Target Sum.py
def targetSum(arr, target):
if not arr or target is None:
return -1
result = []
for i in range(len(arr)):
for j in range(i+1, len(arr)):
if arr[i] + arr[j] == target:
result.append((arr[i], arr[j]))
return result
arr = [1, 2, 3, 4, 5]
target = 7
print(targetSum(arr, target)) # [(2,5), (3,4)]