Recursion (Brute Force)
Intuition
From any cell (i, j), the robot can move right to (i, j+1) or down to (i+1, j). The number of paths from (i, j) to the destination is the sum of paths from the right neighbor and the downward neighbor. The base case is that any cell in the last row or last column has exactly one path (since the robot can only go in one direction).
Algorithm
- If `m == 1` or `n == 1`, return `1`.
- Recursively compute `uniquePaths(m - 1, n) + uniquePaths(m, n - 1)`.
- Return the result.
O(2^(m+n))SpaceO(m + n) for the recursion stackCode (C++ · Java · Python · Go)
class Solution {
public:
int uniquePaths(int m, int n) {
if (m == 1 || n == 1) return 1;
return uniquePaths(m - 1, n) + uniquePaths(m, n - 1);
}
};class Solution {
public int uniquePaths(int m, int n) {
if (m == 1 || n == 1) return 1;
return uniquePaths(m - 1, n) + uniquePaths(m, n - 1);
}
}class Solution:
def uniquePaths(self, m: int, n: int) -> int:
if m == 1 or n == 1:
return 1
return self.uniquePaths(m - 1, n) + self.uniquePaths(m, n - 1)func uniquePaths(m int, n int) int {
if m == 1 || n == 1 {
return 1
}
return uniquePaths(m-1, n) + uniquePaths(m, n-1)
}