Algo-Sim › Dynamic Programming
Combination Sum IV
Medium · Dynamic Programming · step through it in Java, Python and C++ on your own input
Count the ordered sequences of numbers (reusable) that add up to a target: dp[t] sums dp[t − num] over every num.
Problem
Given an array of distinct positive integers nums and a target, return how many sequences of numbers from nums add up to target. Each number may be used any number of times, and sequences in a different order count as different (despite the name, these are permutations).
Constraints
- 1 ≤ nums.length ≤ 200
- 1 ≤ nums[i] ≤ 1000, all distinct
- 1 ≤ target ≤ 1000
- The answer fits in a 32-bit integer
Edge cases to test
- target = 0:
1 - No number fits
- Counts that overflow (they can, despite the task)
Follow-up questions
- What if negative numbers are allowed?
- Infinitely many sequences could sum to the target, so you must cap the length; then the state becomes (target, length).
- How does it differ from Coin Change II?
- Order matters here, so the amount is the outer loop and every number is tried as the last one.
Solution
Java
public int combinationSum4(int[] nums, int target) {
int[] dp = new int[target + 1];
dp[0] = 1;
for (int t = 1; t <= target; t++) {
for (int num : nums) {
if (num <= t) dp[t] += dp[t - num];
}
}
return dp[target];
}Python
def combination_sum4(nums, target):
dp = [0] * (target + 1)
dp[0] = 1
for t in range(1, target + 1):
for num in nums:
if num <= t:
dp[t] += dp[t - num]
return dp[target]C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int combinationSum4(vector<int> &nums, int target) {
vector<int> dp = vector<int>(target + 1);
dp[0] = 1;
for (int t = 1; t <= target; t++) {
for (int num : nums) {
if (num <= t)
dp[t] += dp[t - num];
}
}
return dp[target];
}
};
More Dynamic Programming problems
- Climbing Stairs: Recursion → Memo → Table (Easy)
- Min Cost Climbing Stairs (Easy)
- House Robber (Medium)
- House Robber II (Medium)
- Coin Change (Medium)
- Coin Change II (Medium)
- Perfect Squares (Medium)
- Decode Ways (Medium)
- Maximum Product Subarray (Medium)
- Best Time to Buy and Sell Stock with Cooldown (Medium)
- Best Time to Buy and Sell Stock with Transaction Fee (Medium)
- Best Time to Buy and Sell Stock III (Hard)
- Longest Increasing Subsequence (Medium)
- Word Break (Medium)
- Unique Paths (Medium)
- Unique Paths II (Medium)
- Minimum Path Sum (Medium)
- Maximal Square (Medium)
- Partition Equal Subset Sum (Medium)
- Target Sum (Medium)
- Longest Common Subsequence (Medium)
- Interleaving String (Medium)
- 0/1 Knapsack (Medium)
- Edit Distance (Medium)
- Distinct Subsequences (Hard)
- Longest Palindromic Substring (Medium)
- Palindromic Substrings (Medium)
- Longest Palindromic Subsequence (Medium)
- Predict the Winner (Medium)
- Stone Game (Medium)