Unique Paths (LeetCode)

Question:

https://oj.leetcode.com/problems/unique-paths/

 

经典的DP问题。到达当前点有可能是从左边也有可能是从上边,所以它的可能路径是其左边点的可能路径和上边点的可能路径的和。

一维数组重复利用即可。

 

class Solution {
public:
    int uniquePaths(int m, int n) {
        vector<int> paths(n, 0);
        
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (i == 0)
                    paths[j] = 1;
                else
                    paths[j] += (j > 0 ? paths[j-1] : 0);
            }
        }
        
        return paths[n-1];
    }
};

 

posted @ 2015-01-23 14:51  smileheart  阅读(108)  评论(0)    收藏  举报