Saturday, January 5, 2013

Unique Paths

Solution:

class Solution {
public:
    int uniquePaths(int m, int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (m == 1 || n == 1)
            return 1;
        else {
            return uniquePaths(m, n - 1) + uniquePaths(m - 1, n);
        }
    }
};


DP Solution:

class Solution {
public:
    int uniquePaths(int m, int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
       
        int st[m][n];
        for (int i = 0; i < m ; i++)
            st[i][0] = 1;
        for (int i = 0; i < n ; i++)
            st[0][i] = 1;
       
        for (int i = 1; i < m; i++)
            for (int j = 1; j < n; j++)
                st[i][j] = st[i-1][j] + st[i][j-1];
       
        return st[m-1][n-1];
    }
};

No comments:

Post a Comment