1
1
/* *
2
2
* @file
3
- * @brief Implementation of Unique Paths problem using
4
- * Dynamic Programming (Memoization + Tabulation).
3
+ * @brief Implementation of Unique Paths problem using Dynamic Programming.
5
4
* @details
6
- * A robot is located at the top-left corner of an m x n grid.
5
+ * A robot is located at the top-left corner of an m × n grid.
7
6
* The robot can move either down or right at any point in time.
8
- * The robot is trying to reach the bottom-right corner.
9
- * This program computes the total number of unique paths.
7
+ * This program computes the total number of unique paths to reach
8
+ * the bottom-right corner.
9
+ *
10
+ * Approaches:
11
+ * - **Memoization (Top-Down)**: Recursively explores solutions while
12
+ * storing intermediate results in a cache (`dp`) to avoid redundant
13
+ * computation. Typically more intuitive and easy to write, but
14
+ * relies on recursion and has associated call-stack overhead.
15
+ *
16
+ * - **Tabulation (Bottom-Up)**: Iteratively builds the solution using
17
+ * a DP table, starting from the base cases and filling up the table.
18
+ * Offers consistent performance without recursion overhead and
19
+ * is generally more space-efficient when optimized.
10
20
*
11
21
* @see https://leetcode.com/problems/unique-paths/
12
22
*/
@@ -30,21 +40,6 @@ class UniquePathsSolver {
30
40
std::vector<std::vector<int >> dp; // /< Memoization table
31
41
int m, n;
32
42
33
- /* *
34
- * @brief Recursive + Memoization solution.
35
- * @param i Current row index
36
- * @param j Current column index
37
- * @return int Number of unique paths from (i, j) to (m-1, n-1)
38
- */
39
- int solveMem (int i, int j) {
40
- if (i >= m || j >= n) return 0 ;
41
- if (i == m - 1 && j == n - 1 ) return 1 ;
42
- if (dp.at (i).at (j) != -1 ) return dp.at (i).at (j);
43
-
44
- dp.at (i).at (j) = solveMem (i + 1 , j) + solveMem (i, j + 1 );
45
- return dp.at (i).at (j);
46
- }
47
-
48
43
/* *
49
44
* @brief Bottom-up Tabulation solution.
50
45
* @return int Number of unique paths from (0, 0) to (m-1, n-1)
@@ -72,12 +67,19 @@ class UniquePathsSolver {
72
67
}
73
68
74
69
/* *
75
- * @brief Get number of unique paths using Memoization
70
+ * @brief Get number of unique paths using Memoization (Top-Down)
76
71
*/
77
- int uniquePathsMemo () { return solveMem (0 , 0 ); }
72
+ int uniquePathsMemo (int i = 0 , int j = 0 ) {
73
+ if (i >= m || j >= n) return 0 ;
74
+ if (i == m - 1 && j == n - 1 ) return 1 ;
75
+ if (dp.at (i).at (j) != -1 ) return dp.at (i).at (j);
76
+
77
+ dp.at (i).at (j) = uniquePathsMemo (i + 1 , j) + uniquePathsMemo (i, j + 1 );
78
+ return dp.at (i).at (j);
79
+ }
78
80
79
81
/* *
80
- * @brief Get number of unique paths using Tabulation
82
+ * @brief Get number of unique paths using Tabulation (Bottom-Up)
81
83
*/
82
84
int uniquePathsTab () { return solveTab (); }
83
85
};
0 commit comments