Problem 377

Abstract / Summary

Given a list of numbers and a target find how many ways to make the target using numbers where each can be used any number of times

Note

The full problem description, including helpful examples, can be found on LeetCode.

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];
    }
};
16 lines | 444 bytes | submitted August 8, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 55% (1+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Dynamic Programming
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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 condition base < target fails, and the function returns 1, 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 every base, 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 target is zero, the function returns 1; 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 any base that 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 double for 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 6 | μ = 6.04 | σ = 1.69

Complexity Analysis

Time: polynomial
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
47 links | 31 authors | 11 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

19 easy 42 medium 2 hard
64 solutions   August 8, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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