Skip to content

Commit df740a0

Browse files
authored
Update unique_paths.cpp
1 parent d7f9c60 commit df740a0

File tree

1 file changed

+7
-5
lines changed

1 file changed

+7
-5
lines changed

dynamic_programming/unique_paths.cpp

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ namespace dynamic_programming {
4040
*/
4141
class UniquePathsSolver {
4242
private:
43-
std::vector<std::vector<int>> memoization_table; ///< Memoization table to cache intermediate results
43+
std::vector<std::vector<int>> memoization_table; ///< Memoization table to cache intermediate results (-1 = uncomputed)
4444
std::size_t m; ///< Number of rows in the grid
4545
std::size_t n; ///< Number of columns in the grid
4646

@@ -51,11 +51,13 @@ class UniquePathsSolver {
5151
int solveTabulation() {
5252
std::vector<std::vector<int>> table(m, std::vector<int>(n, 0));
5353

54-
for (std::size_t i = 0; i < m; i++) table[i][n - 1] = 1; ///< last column
55-
for (std::size_t j = 0; j < n; j++) table[m - 1][j] = 1; ///< last row
54+
// base cases: last column and last row
55+
for (std::size_t i = 0; i < m; i++) table[i][n - 1] = 1;
56+
for (std::size_t j = 0; j < n; j++) table[m - 1][j] = 1;
5657

57-
for (int i = static_cast<int>(m) - 2; i >= 0; i--) {
58-
for (int j = static_cast<int>(n) - 2; j >= 0; j--) {
58+
// fill the table from bottom-right to top-left
59+
for (std::size_t i = m - 1; i-- > 0;) {
60+
for (std::size_t j = n - 1; j-- > 0;) {
5961
table[i][j] = table[i + 1][j] + table[i][j + 1];
6062
}
6163
}

0 commit comments

Comments
 (0)