C++ 0377.cpp
class Solution {
public:
int combinationSum4(vector<int>& nums, int target) {
vector<double> ways;
ways.resize(target + 1, 0);
ways[0] = 1;
for (int base = 0; base < target; base++)
for (auto c : nums)
if (ways[base] > 0)
if (base + c < ways.size())
ways[base + c] += ways[base];
return ways[target];
}
};
Difficulty
and has an acceptance rate of about 55% (1+ million submissions).
Typical patterns to solve this problem:
- Array
- Dynamic Programming
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the “Combination Sum IV” problem using a dynamic-programming (DP) approach. It builds a one-dimensional DP table ways where each entry ways[i] stores the number of ordered combinations that sum to the value i. The algorithm iterates over all possible intermediate sums (base) and, for each, propagates the count to reachable sums by adding each element from nums. The final answer is the value stored at ways[target].
Key Steps
DP table allocation and initialization
vector<double> ways;
ways.resize(target + 1, 0);
ways[0] = 1;
A vector of length target + 1 is created and filled with zeros. The entry for sum 0 is set to 1, representing the empty combination that yields a total of zero. Using double allows the table to hold very large counts without overflow that could occur with a 32-bit integer type.
Main iteration over base sums
for (int base = 0; base < target; base++)
for (auto c : nums)
if (ways[base] > 0)
if (base + c < ways.size())
ways[base + c] += ways[base];
The outer loop walks through every possible intermediate sum base from 0 up to target-1. For each base, the inner loop examines every candidate number c from the input array.
- The guard
if (ways[base] > 0)skips work for sums that cannot be formed, preventing unnecessary updates. - The second guard
if (base + c < ways.size())ensures that the algorithm never writes beyond the allocated vector, automatically discarding numbers that would exceed the target.
When both conditions hold, the count for the new sum base + c is increased by the number of ways to reach base. This accumulation naturally counts ordered sequences because each extension is considered in the order of iteration.
Returning the result
return ways[target];
After all reachable sums have been processed, the entry at index target holds the total number of ordered combinations that sum exactly to the required value.
Edge Cases Handled
-
Target equal to zero - The DP table is initialized with
ways[0] = 1. The loops never execute because the outer loop conditionbase < targetfails, and the function returns1, correctly representing the single empty combination. -
Numbers larger than the target - The inner guard
base + c < ways.size()prevents any addition that would exceed the target, effectively ignoring such numbers without extra preprocessing. -
Duplicate values in
nums- Because each element is processed independently for everybase, duplicate values contribute proportionally to the count, preserving the intended combinatorial semantics. -
Empty input array - With no elements to iterate, the inner loop body never runs. If
targetis zero, the function returns1; otherwise,ways[target]remains zero, indicating that no combination can achieve a positive target.
Performance Optimizations
-
Single-dimensional DP array - By reusing a one-dimensional vector, the algorithm keeps memory usage linear in the target value, avoiding the overhead of a two-dimensional table.
-
Early skip of unreachable bases - The condition
if (ways[base] > 0)eliminates the inner loop for anybasethat cannot be formed, reducing the number of inner-loop iterations dramatically when many intermediate sums are impossible. -
Bounds check before update - The test
base + c < ways.size()ensures that only valid indices are accessed, allowing the compiler to generate tight loop code without additional branching for out-of-range cases. -
Use of
doublefor accumulation - Storing counts in a floating-point type avoids the need for explicit overflow checks or larger integer types, enabling the algorithm to handle very large result values with a single arithmetic operation per update.
Overall, the code follows a clear DP formulation, leverages early pruning of irrelevant states, and maintains a compact memory footprint while correctly handling a variety of edge conditions.
ELI5 - Simplified Explanation
Imagine you have a big pile of building blocks and you want to see how many different ways you can stack them up to reach exactly a certain height. The computer creates a long row of little boxes, each one representing a different height from zero all the way up to the target height you picked. The box at the very beginning is marked with a one, which is like a starting secret that helps the math work out.
The computer then looks at every small height one by one. For each height, it checks your pile of blocks to see which sizes you have available. If a block fits on top of the current height without going past the goal, the computer takes the number of ways it already found to reach the current height and adds that to the box for the new, taller height. This happens over and over again, moving through every possible height until the final box shows the total number of ways to build the target height.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||||
| www | AlgoMonster | C++ | Java | Python | TS | |||||||
| WalkCCC | C++ | Java | Python | |||||||||
| leetcode.ca | C++ | Java | Python | JS | Go | C# | TS | |||||
| LeetcodeHelp | C++ | Java | Python | |||||||||
| MemoryLimitExceeded | C++ | Python | ||||||||||
| Progiez | C++ | Java | Python | |||||||||
| github | black-shadows | C++ | ||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| DimitrisJim | C | |||||||||||
| everthis | JS | |||||||||||
| fartem | Ruby | |||||||||||
| fengvyi | C++ | |||||||||||
| fpdjsns | Python | |||||||||||
| gouthampradhan | Java | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JS | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| MacJim | C++ | |||||||||||
| ruoru | Rust | |||||||||||
| suxrobGM | C# | |||||||||||
| trung-hn | Python | |||||||||||
| varunu28 | Java | |||||||||||
| vli02 | C | |||||||||||
| vthwang | Java | |||||||||||
| wisdompeak | C++ | |||||||||||
| XiaotaoGuo | C++ | |||||||||||
| yuanliu666 | Kotlin | |||||||||||
| zfang399 | C++ | |||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||
| WalkCCC | C++, Python, Java | |||||||||||
| leetcode.ca | C++, C#, Go, Java, JavaScript, Python, TypeScript | |||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||||
| Progiez | C++, Java, Python | |||||||||||
| black-shadows | C++, C++ | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| DimitrisJim | C | |||||||||||
| everthis | JavaScript | |||||||||||
| fartem | Ruby | |||||||||||
| fengvyi | C++ | |||||||||||
| fpdjsns | Python | |||||||||||
| gouthampradhan | Java | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JavaScript | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| MacJim | C++ | |||||||||||
| ruoru | Rust | |||||||||||
| suxrobGM | C# | |||||||||||
| trung-hn | Python | |||||||||||
| varunu28 | Java | |||||||||||
| vli02 | C | |||||||||||
| vthwang | Java | |||||||||||
| wisdompeak | C++ | |||||||||||
| XiaotaoGuo | C++ | |||||||||||
| yuanliu666 | Kotlin | |||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 39: Combination Sum
Solved On The Same Day
- problem 1: Two Sum
- problem 9: Palindrome Number
- problem 14: Longest Common Prefix
- problem 20: Valid Parentheses
- problem 26: Remove Duplicates from Sorted Array
- problem 27: Remove Element
- problem 83: Remove Duplicates from Sorted List
- problem 88: Merge Sorted Array
- problem 94: Binary Tree Inorder Traversal
- problem 100: Same Tree
- problem 104: Maximum Depth of Binary Tree
- problem 121: Best Time to Buy and Sell Stock
- problem 136: Single Number
- problem 141: Linked List Cycle
- problem 169: Majority Element
- problem 190: Reverse Bits
- problem 226: Invert Binary Tree
- problem 234: Palindrome Linked List
- problem 1114: Print in Order
- problem 3: Longest Substring Without Repeating Characters
- problem 7: Reverse Integer
- problem 8: String to Integer (atoi)
- problem 11: Container With Most Water
- problem 12: Integer to Roman
- problem 15: 3Sum
- problem 17: Letter Combinations of a Phone Number
- problem 22: Generate Parentheses
- problem 31: Next Permutation
- problem 36: Valid Sudoku
- problem 39: Combination Sum
- problem 40: Combination Sum II
- problem 45: Jump Game II
- problem 46: Permutations
- problem 47: Permutations II
- problem 48: Rotate Image
- problem 49: Group Anagrams
- problem 55: Jump Game
- problem 59: Spiral Matrix II
- problem 75: Sort Colors
- problem 77: Combinations
- problem 91: Decode Ways
- problem 95: Unique Binary Search Trees II
- problem 96: Unique Binary Search Trees
- problem 134: Gas Station
- problem 164: Maximum Gap
- problem 189: Rotate Array
- problem 215: Kth Largest Element in an Array
- problem 238: Product of Array Except Self
- problem 287: Find the Duplicate Number
- problem 322: Coin Change
- problem 347: Top K Frequent Elements
- problem 438: Find All Anagrams in a String
- problem 474: Ones and Zeroes
- problem 518: Coin Change II
- problem 526: Beautiful Arrangement
- problem 763: Partition Labels
- problem 983: Minimum Cost For Tickets
- problem 994: Rotting Oranges
- problem 1027: Longest Arithmetic Subsequence
- problem 2140: Solving Questions With Brainpower
- problem 2466: Count Ways To Build Good Strings
- problem 4: Median of Two Sorted Arrays
- problem 41: First Missing Positive
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality