Given an array of distinct integers
numsand a target integertarget, return the number of possible combinations that add up totarget.The test cases are generated so that the answer can fit in a 32-bit integer.
Constraints:
1 <= nums.length <= 2001 <= nums[i] <= 1000- All the elements of
numsare unique.1 <= target <= 1000
Let be the number of possible combinations that add up to , from the array of integers . Then:
def combinationSum4(nums: List[int], target: int) -> int:
solutions = {}
def countCombinations(nums: List[int], t: int) -> int:
if t in solutions: return solutions[t]
if t < 0:
solutions[t] = 0
elif t == 0:
solutions[t] = 1
else:
solutions[t] = sum(countCombinations(nums, t - num)
for num in nums)
return solutions[t]
return countCombinations(nums, target)
def combinationSum4(nums: List[int], target: int) -> int:
solutions = {}
for i in range(target + 1):
solutions[i] = 0
for num in nums:
if num == i:
solutions[i] += 1
if i - num in solutions:
solutions[i] += solutions[i - num]
return solutions[target]
Let be the target number and be the number of integers in nums. There are iterations in the outer loop. Each iteration takes time, since the inner loop has iterations each with constant time. Therefore the total time complexity is in .
Since the solutions for every number smaller than must be memoised, the total space complexity is .