C++ 0062.cpp
class Solution {
public:
int uniquePaths(int m, int n) {
vector<vector<int>> board;
board.resize(m);
for (auto& b : board)
b.resize(n);
board[0][0] = 1;
for (int x = 0; x < m; x++)
for (int y = 0; y < n; y++)
{
if (x > 0)
board[x][y] += board[x-1][y];
if (y > 0)
board[x][y] += board[x][y-1];
}
return board[m-1][n-1];
}
};
Difficulty
and has an acceptance rate of about 67% (4+ million submissions).
Typical patterns to solve this problem:
- Combinatorics
- Dynamic Programming
- Math
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 computes the number of distinct paths from the top-left corner to the bottom-right corner of an m-by-n grid, moving only down or right. It builds a two-dimensional dynamic programming table, initializes the starting cell, propagates path counts across the grid, and finally returns the value stored in the destination cell.
Key Steps
The algorithm proceeds through a clear sequence of operations.
The first step creates a matrix named board that will hold the cumulative path counts. The matrix is sized to m rows and n columns using resize calls.
vector<vector<int>> board;
board.resize(m);
for (auto& b : board)
b.resize(n);
Next, the starting position at the top-left corner is seeded with a count of one, representing the single way to be at the origin.
board[0][0] = 1;
The core of the solution is a double loop that iterates over every cell in row-major order. For each cell, the algorithm adds the number of ways to reach the cell directly above (if such a cell exists) and the number of ways to reach the cell directly to the left (if such a cell exists). This accumulation builds the total number of ways to arrive at the current cell.
for (int x = 0; x < m; x++)
for (int y = 0; y < n; y++)
{
if (x > 0)
board[x][y] += board[x-1][y];
if (y > 0)
board[x][y] += board[x][y-1];
}
Finally, the value stored in the bottom-right cell, board[m-1][n-1], is returned as the answer.
return board[m-1][n-1];
Edge Cases Handled
When either m or n equals one, the grid collapses to a single row or a single column. The loops still execute, but the conditional checks if (x > 0) and if (y > 0) prevent out-of-bounds accesses. In a one-row grid, the x > 0 condition never holds, so each cell accumulates only the value from its left neighbor, correctly yielding a single path. Similarly, in a one-column grid, only the x > 0 branch contributes, also resulting in a single path.
The initialization of board[0][0] to one ensures that even the smallest grid (1 × 1) returns a count of one, representing the trivial path that starts and ends at the same cell.
Performance Optimizations
The implementation allocates the DP table once and reuses it throughout the computation, avoiding repeated memory allocations inside the loops. By resizing each row after the outer resize(m), the code guarantees contiguous storage for each inner vector, which improves cache locality when accessing board[x][y].
The nested loops iterate in a straightforward row-major order, allowing the processor to prefetch successive memory locations efficiently. The conditional checks guard against unnecessary additions for the first row and first column, eliminating redundant operations.
Because the algorithm updates each cell exactly once, the overall work scales linearly with the number of cells in the grid, making the approach suitable for moderate grid sizes without incurring extra overhead from recursion or auxiliary data structures.
Concluding Remarks
The solution follows a classic dynamic programming pattern, translating the combinatorial recurrence into an iterative table fill. It correctly addresses boundary conditions, leverages contiguous memory layout for speed, and maintains a clean, readable structure that aligns with typical C++ idioms for matrix manipulation.
ELI5 - Simplified Explanation
Imagine you have a big square grid made of many little boxes on the floor, and you want to walk from the very top corner to the very bottom corner. There are many different paths you could take. To figure out how many ways there are, the computer builds a special map where each box remembers how many ways you can get there.
First, the computer creates a grid of boxes that is exactly as long and as wide as the path you want to walk. At the very start, it places a number one because there is only one way to be at the beginning.
Then, the computer goes through every single box one by one. For any box, it looks at the box just above it and the box just to the left of it. It adds together the numbers written in those two neighbors and writes that new sum in the current box. This is like saying that if you can get to the top neighbor in five ways and the left neighbor in three ways, then you have eight different ways to reach the current spot.
By the time the computer fills in every box all the way to the end of the room, the last box holds the answer for how many total paths exist to reach that corner.
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 | |||||
| LeetcodeHelp | C++ | Python | Java | |||||||||
| MemoryLimitExceeded | C++ | Python | ||||||||||
| Progiez | C++ | Python | Java | |||||||||
| github | aylei | Rust | ||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++ | |||||||||||
| chandansgowda | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| everthis | JS | |||||||||||
| fartem | Ruby | |||||||||||
| FelixFan1122 | C# | |||||||||||
| fengvyi | C++ | |||||||||||
| fpdjsns | C++ | |||||||||||
| gaosq0604 | Python | |||||||||||
| Garvit244 | Python | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JS | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| Krazune | Java | |||||||||||
| lennylxx | C | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| luangong | C++ | |||||||||||
| MacJim | C++ | |||||||||||
| qiyuangong | Python | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| suxrobGM | C# | |||||||||||
| 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, Python, Rust, TypeScript | |||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||||
| Progiez | C++, Java, Python | |||||||||||
| aylei | Rust | |||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++, C++ | |||||||||||
| chandansgowda | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| everthis | JavaScript | |||||||||||
| fartem | Ruby | |||||||||||
| FelixFan1122 | C# | |||||||||||
| fengvyi | C++ | |||||||||||
| fpdjsns | C++ | |||||||||||
| gaosq0604 | Python | |||||||||||
| Garvit244 | Python | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JavaScript | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| Krazune | Java | |||||||||||
| lennylxx | C | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| luangong | C++ | |||||||||||
| MacJim | C++ | |||||||||||
| qiyuangong | Python | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| suxrobGM | C# | |||||||||||
| varunu28 | Java | |||||||||||
| vli02 | C | |||||||||||
| vthwang | Java | |||||||||||
| XiaotaoGuo | C++ | |||||||||||
| yuanliu666 | Kotlin | |||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 63: Unique Paths II
- problem 64: Minimum Path Sum
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 70: Climbing Stairs
- 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 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