Complete-Preparation

🎉 One-stop destination for all your technical interview Preparation 🎉

View the Project on GitHub

Unique Paths 🌟🌟

Recursive Solution

Code

int f(int m, int n, int r, int c)
{
    if (r < 0 || c < 0) return 0;
    if (r == 0 && c == 0) return 1;
    return f(m, n, r - 1, c) + f(m, n, r, c - 1);
}
int uniquePaths(int m, int n)
{
    return f(m, n, m - 1, n - 1);
}

Memoization(top-down)

Code

int f(int m, int n, int r, int c, vector<vector<int>> &dp)
{
    if (r < 0 || c < 0) return 0;
    if (r == 0 && c == 0) return 1;
    if (dp[r][c] != -1) return dp[r][c];
    return dp[r][c] = f(m, n, r - 1, c, dp) + f(m, n, r, c - 1, dp);
}
int uniquePaths(int m, int n)
{
    vector<vector<int>> dp(m, vector<int>(n, -1));
    return f(m, n, m - 1, n - 1, dp);
}

Tabulation(bottom-up)

Code

int uniquePaths(int m, int n)
{
    vector<vector<int>> dp(m, vector<int>(n, 0));
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            if (i == 0 || j == 0)
                dp[i][j] = 1;
            else
                dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
        }
    }
    return dp[m - 1][n - 1];
}

Space optimized Tabulation(bottom-up)

Code

int uniquePaths(int m, int n)
{
    vector<int> prevRow(n, 0); // n size row
    for (int i = 0; i < m; i++) {
        vector<int> currRow(n, 0);
        for (int j = 0; j < n; j++) {
            if (i == 0 || j == 0)
                currRow[j] = 1;
            else
                currRow[j] = prevRow[j] + currRow[j - 1];
        }
        prevRow = currRow;
    }
    return prevRow[n - 1];
}