Combination Sum IV — LeetCode 377 Python Solution
- Problem
- #377
- Pattern
- Dynamic Programming
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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.
Example
- Input
- nums = [1,2,3], target = 4
- Output
- 7
- Explanation
- The possible combination ways are:
Python solution
class Solution:
def combinationSum4(self, nums: List[int], target: int) -> int:
f = [1] + [0] * target
for i in range(1, target + 1):
for x in nums:
if i >= x:
f[i] += f[i - x]
return f[target]Complexity
| Measure | Complexity |
|---|---|
| Time | O(n \times target) |
| Space | O(target), where n is the length of the array auxiliary |
Pattern: Dynamic Programming
Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 377. Combination Sum IV is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.
The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.
Related problems
On a study list
This problem is on Blind 75.
Frequently asked questions
- How hard is LeetCode 377. Combination Sum IV?
- LeetCode 377. Combination Sum IV is rated Medium on LeetCode.
- What is the time complexity of LeetCode 377. Combination Sum IV?
- The Python solution on this page runs in O(n \times target).
- What is the space complexity of LeetCode 377. Combination Sum IV?
- The Python solution on this page uses O(target), where n is the length of the array auxiliary space.
- What topics does LeetCode 377. Combination Sum IV cover?
- LeetCode 377. Combination Sum IV is tagged Array and Dynamic Programming on LeetCode.