C++ 0070.cpp
class Solution {
vector<int> cache;
int dp(int current, int total)
{
if (current > total)
return 0;
if (current == total)
return 1;
if (cache[current] >= 0)
return cache[current];
int one = dp(current + 1, total);
int two = dp(current + 2, total);
int result = one + two;
cache[current] = result;
return result;
}
public:
int climbStairs(int n) {
cache.clear();
cache.resize(50, -1);
return dp(0, n);
}
};
Difficulty
and has an acceptance rate of about 54% (9+ million submissions).
Typical patterns to solve this problem:
- Dynamic Programming
- Math
- Memoization
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 presented implementation solves the classic combinatorial problem of counting distinct ways to ascend a staircase when each step can be either a single or a double stride. The solution employs a depth-first recursion augmented with memoization to avoid redundant sub-problem evaluations. The public interface climbStairs prepares the memoization structure and initiates the recursive exploration from the ground level.
Core Logic
At the heart of the algorithm lies the recursive helper dp. It receives two parameters: current, the index of the step currently occupied, and total, the target step count. The function first checks whether the traversal has overshot the destination; in that case it returns zero, indicating an invalid path. When the exact target is reached, it returns one, signifying a successful way to climb the stairs.
int dp(int current, int total)
{
if (current > total)
return 0;
if (current == total)
return 1;
// ...
}
If the result for the current position has already been computed, the cached value is returned immediately, preventing duplicate work. Otherwise the function explores the two permissible moves: advancing by one step and by two steps. The results of these two recursive calls are summed to produce the total number of ways from the current position, stored in the cache, and then returned.
if (cache[current] >= 0)
return cache[current];
int one = dp(current + 1, total);
int two = dp(current + 2, total);
int result = one + two;
cache[current] = result;
return result;
Memoization Strategy
The memoization container cache is a vector<int> that holds pre-computed results for each possible step index. Before any recursion begins, climbStairs clears any existing content and resizes the vector to a fixed capacity of 50 elements, initializing each entry to -1 to denote an uncomputed state. This size comfortably exceeds typical input ranges for the problem while keeping memory usage predictable.
int climbStairs(int n) {
cache.clear();
cache.resize(50, -1);
return dp(0, n);
}
By indexing directly with the current step, the algorithm achieves constant-time access to previously solved sub-problems, which dramatically reduces the exponential blow-up inherent in naïve recursion.
Edge Cases Handled
The implementation explicitly addresses the scenario where the recursion steps beyond the target (current > total). Returning zero in this branch ensures that overshooting paths do not contribute to the final count. The exact match case (current == total) returns one, correctly counting the scenario where the staircase has been climbed precisely. These two base conditions together guarantee that all possible traversal paths are evaluated accurately, including the minimal input where n equals zero (the function will return one, representing the empty sequence of moves).
Performance Optimizations
The primary optimization stems from the memoization cache, which transforms the recursive exploration from an exponential to a linear number of distinct sub-problem evaluations. By storing each intermediate result after its first computation, subsequent calls for the same current index bypass the recursive descent entirely. The fixed cache size eliminates the overhead of dynamic resizing during recursion, and the use of a simple integer vector ensures low-level memory locality, which benefits CPU cache performance. Additionally, the early return checks for out-of-bounds and exact matches prevent unnecessary recursive calls, further trimming the execution path.
ELI5 - Simplified Explanation
Imagine there is a tall staircase with many steps, and there is a little person who wants to get to the very top. To climb the stairs, this person can either jump up one step at a time or take a big leap of two steps at once. The code is like a clever helper that counts all the different ways to reach the top. It starts at the bottom and keeps track of every choice made, like choosing a tiny step or a big jump.
Because there are so many ways to climb, it could take a very long time to count them one by one. To stay fast, the helper keeps a special notebook called a cache. Whenever the helper figures out how many ways there are to finish the climb from a certain step, that number gets written down in the notebook. If the helper ever needs to know that same information again, it just peeks at the notebook instead of doing all the hard work over again.
The main part of the code gets everything ready by clearing the notebook and giving it plenty of space to remember things. Then, it sends the helper off to start at the bottom step and climb all the way to the end. The helper follows the simple rule of trying both the one-step and two-step moves, writing down the answers as it goes, until every path to the top is counted.
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++ | Python | Java | TS | ||||||||
| WalkCCC | C++ | Python | Java | ||||||||||
| leetcode.ca | C++ | Python | Java | Rust | JS | Go | TS | PHP | |||||
| LeetcodeHelp | C++ | Python | Java | ||||||||||
| MemoryLimitExceeded | C++ | Python | |||||||||||
| Progiez | C++ | Python | Java | ||||||||||
| github | aylei | Rust | |||||||||||
| begeekmyfriend | C | ||||||||||||
| BigEggStudy | C# | ||||||||||||
| black-shadows | C++ | ||||||||||||
| bujosa | Python | ||||||||||||
| chandansgowda | Python | ||||||||||||
| charles-wangkai | Java | ||||||||||||
| chenyanzhe | C++ | ||||||||||||
| DimitrisJim | C | ||||||||||||
| everthis | JS | ||||||||||||
| fartem | Ruby | ||||||||||||
| FelixFan1122 | C# | ||||||||||||
| fengvyi | C++ | ||||||||||||
| fpdjsns | C++ | ||||||||||||
| gaosq0604 | Python | ||||||||||||
| Garvit244 | Python | ||||||||||||
| gouthampradhan | Java | ||||||||||||
| halfrost | Go | ||||||||||||
| JoshCrozier | JS | ||||||||||||
| keineahnung2345 | C++ | ||||||||||||
| lennylxx | C | ||||||||||||
| linouk23 | C++ | ||||||||||||
| lkwq007 | Python | ||||||||||||
| luangong | C++ | TS | |||||||||||
| MacJim | C++ | ||||||||||||
| muhammadfarhankt | Go | ||||||||||||
| pruthvikp | Python | ||||||||||||
| qiyuangong | Python | ||||||||||||
| ruoru | Rust | ||||||||||||
| shreymehul | C# | ||||||||||||
| sonugiri1043 | C++ | ||||||||||||
| suxrobGM | Java | ||||||||||||
| varunu28 | Java | ||||||||||||
| vli02 | C | ||||||||||||
| vthwang | Java | ||||||||||||
| XiaotaoGuo | C++ | ||||||||||||
| yuanliu666 | Kotlin | ||||||||||||
| zfang399 | C++ | ||||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||||
| WalkCCC | C++, Python, Java | ||||||||||||
| leetcode.ca | C++, Go, Java, JavaScript, PHP, Python, Rust, TypeScript | ||||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||||||
| Progiez | C++, Java, Python | ||||||||||||
| aylei | Rust | ||||||||||||
| begeekmyfriend | C | ||||||||||||
| BigEggStudy | C# | ||||||||||||
| black-shadows | C++, C++ | ||||||||||||
| bujosa | Python | ||||||||||||
| chandansgowda | Python | ||||||||||||
| charles-wangkai | Java | ||||||||||||
| chenyanzhe | C++ | ||||||||||||
| DimitrisJim | C | ||||||||||||
| everthis | JavaScript | ||||||||||||
| fartem | Ruby | ||||||||||||
| FelixFan1122 | C# | ||||||||||||
| fengvyi | C++ | ||||||||||||
| fpdjsns | C++ | ||||||||||||
| gaosq0604 | Python | ||||||||||||
| Garvit244 | Python | ||||||||||||
| gouthampradhan | Java | ||||||||||||
| halfrost | Go | ||||||||||||
| JoshCrozier | JavaScript | ||||||||||||
| keineahnung2345 | C++ | ||||||||||||
| lennylxx | C | ||||||||||||
| linouk23 | C++ | ||||||||||||
| lkwq007 | Python | ||||||||||||
| luangong | C++, TypeScript | ||||||||||||
| MacJim | C++ | ||||||||||||
| muhammadfarhankt | Go | ||||||||||||
| pruthvikp | Python | ||||||||||||
| qiyuangong | Python | ||||||||||||
| ruoru | Rust | ||||||||||||
| shreymehul | C# | ||||||||||||
| sonugiri1043 | C++ | ||||||||||||
| suxrobGM | Java | ||||||||||||
| varunu28 | Java | ||||||||||||
| vli02 | C | ||||||||||||
| vthwang | Java | ||||||||||||
| XiaotaoGuo | C++ | ||||||||||||
| yuanliu666 | Kotlin | ||||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 509: Fibonacci Number
- problem 746: Min Cost Climbing Stairs
- problem 2244: Minimum Rounds to Complete All Tasks
- problem 2466: Count Ways To Build Good Strings
Solved On The Same Day
- problem 13: Roman to Integer
- problem 21: Merge Two Sorted Lists
- problem 28: Find the Index of the First Occurrence in a String
- problem 35: Search Insert Position
- problem 58: Length of Last Word
- problem 66: Plus One
- problem 67: Add Binary
- problem 69: Sqrt(x)
- problem 206: Reverse Linked List
- problem 242: Valid Anagram
- problem 278: First Bad Version
- problem 283: Move Zeroes
- problem 367: Valid Perfect Square
- problem 374: Guess Number Higher or Lower
- problem 389: Find the Difference
- problem 441: Arranging Coins
- problem 459: Repeated Substring Pattern
- problem 509: Fibonacci Number
- problem 657: Robot Return to Origin
- problem 682: Baseball Game
- problem 704: Binary Search
- problem 709: To Lower Case
- problem 744: Find Smallest Letter Greater Than Target
- problem 746: Min Cost Climbing Stairs
- problem 860: Lemonade Change
- problem 896: Monotonic Array
- problem 976: Largest Perimeter Triangle
- problem 1137: N-th Tribonacci Number
- problem 1232: Check If It Is a Straight Line
- problem 1275: Find Winner on a Tic Tac Toe Game
- problem 1351: Count Negative Numbers in a Sorted Matrix
- problem 1491: Average Salary Excluding the Minimum and Maximum Salary
- problem 1502: Can Make Arithmetic Progression From Sequence
- problem 1523: Count Odd Numbers in an Interval Range
- problem 1539: Kth Missing Positive Number
- problem 1572: Matrix Diagonal Sum
- problem 1672: Richest Customer Wealth
- problem 1768: Merge Strings Alternately
- problem 1822: Sign of the Product of an Array
- problem 2: Add Two Numbers
- problem 5: Longest Palindromic Substring
- problem 33: Search in Rotated Sorted Array
- problem 34: Find First and Last Position of Element in Sorted Array
- problem 43: Multiply Strings
- problem 50: Pow(x, n)
- problem 54: Spiral Matrix
- problem 62: Unique Paths
- problem 63: Unique Paths II
- problem 64: Minimum Path Sum
- problem 73: Set Matrix Zeroes
- problem 74: Search a 2D Matrix
- problem 120: Triangle
- problem 139: Word Break
- problem 153: Find Minimum in Rotated Sorted Array
- problem 198: House Robber
- problem 221: Maximal Square
- problem 275: H-Index II
- problem 279: Perfect Squares
- problem 300: Longest Increasing Subsequence
- problem 436: Find Right Interval
- problem 445: Add Two Numbers II
- problem 528: Random Pick with Weight
- problem 540: Single Element in a Sorted Array
- problem 611: Valid Triangle Number
- problem 658: Find K Closest Elements
- problem 852: Peak Index in a Mountain Array
- problem 981: Time Based Key-Value Store
- problem 1041: Robot Bounded In Circle
- problem 1146: Snapshot Array
- problem 2300: Successful Pairs of Spells and Potions
- problem 154: Find Minimum in Rotated Sorted Array II
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