Home Leetcode

377. Combination Sum IV

Given an array of distinct integers nums and a target integer target, return the number of possible combinations that add up to target.

The test cases are generated so that the answer can fit in a 32-bit integer.

Constraints:

Let OPT(t)OPT(t) be the number of possible combinations that add up to tt, from the array of integers AA. Then:

OPT(t)={0t<01t=0aAOPT(ta)elseOPT(t) = \begin{cases} 0 & t < 0 \\ 1 & t = 0 \\ \sum_{a \in A} OPT(t - a) & \text{else} \end{cases}

Top-Down

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)
	

Bottom-Up

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]

Time Complexity

Let tt be the target number and nn be the number of integers in nums. There are tt iterations in the outer loop. Each iteration takes O(n)\mathcal{O}(n) time, since the inner loop has nn iterations each with constant time. Therefore the total time complexity is in O(nt)\mathcal{O}(n \cdot t).

Space Complexity

Since the solutions for every number smaller than tt must be memoised, the total space complexity is O(t)\mathcal{O}(t).