File tree Expand file tree Collapse file tree 1 file changed +7
-5
lines changed Expand file tree Collapse file tree 1 file changed +7
-5
lines changed Original file line number Diff line number Diff line change @@ -40,7 +40,7 @@ namespace dynamic_programming {
40
40
*/
41
41
class UniquePathsSolver {
42
42
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)
44
44
std::size_t m; // /< Number of rows in the grid
45
45
std::size_t n; // /< Number of columns in the grid
46
46
@@ -51,11 +51,13 @@ class UniquePathsSolver {
51
51
int solveTabulation () {
52
52
std::vector<std::vector<int >> table (m, std::vector<int >(n, 0 ));
53
53
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 ;
56
57
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 ;) {
59
61
table[i][j] = table[i + 1 ][j] + table[i][j + 1 ];
60
62
}
61
63
}
You can’t perform that action at this time.
0 commit comments