MediumNo. 0377
Combination Sum IV — LeetCode 377 Python Solution
- Pattern
- Dynamic Programming
- Topics
- Array, Dynamic Programming
- On a study list
- Blind 75
- 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
- Time
- O(n × target)
- Space · auxiliary
- O(target)where n is the length of the array
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
| No. | Problem | Difficulty |
|---|---|---|
| 0039 | Combination Sum | Medium |
| 0376 | Wiggle Subsequence | Medium |
| 0368 | Largest Divisible Subset | Medium |
| 0045 | Jump Game II | Medium |
| 0053 | Maximum Subarray | Medium |
| 0055 | Jump Game | Medium |
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 × 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.