码迷,mamicode.com
首页 > 其他好文 > 详细

Unique Paths

时间:2015-05-17 16:33:35      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:

class Solution {
public:
    int uniquePaths(int m, int n) {
        vector> res(m);
        for(int i=0;i
            res[i].resize(n);
        if(m<0||n<0)
            return 0;
        if(m==1||n==1)
            return 1;
        res[0][0]=0;
        res[0][1]=1;
        res[1][0]=1;
        for(int i=0;i
            for(int j=0;j
            {
                if(i==0||j==0)
                 
                        res[i][j]=1;
                else
                    res[i][j]=res[i][j-1]+res[i-1][j];
                
            }
            
        return res[m-1][n-1];
        
    }
};
 
网上看到一种比这个熟练的方法
开一个f[m][n]的数组,f[i][j] = f[i-1][j] + f[i][j-1],空间时间复杂度O(m*n)。用滚动数组空间复杂度可降为O(n);
来自:http://www.cnblogs.com/remlostime/archive/2012/11/15/2772263.html
1 class Solution {
 2 public:
 3     int uniquePaths(int m, int n) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         vector > f(m, vector(n));
 7         
 8         for(int i = 0; i < n; i++)
 9             f[0][i] = 1;
10             
11         for(int i = 0; i < m; i++)
12             f[i][0] = 1;
13             
14         for(int i = 1; i < m; i++)
15             for(int j = 1; j < n; j++)
16                 f[i][j] = f[i-1][j] + f[i][j-1];
17                 
18         return f[m-1][n-1];
19     }
20 };

 

Unique Paths

标签:

原文地址:http://www.cnblogs.com/qiaozhoulin/p/4509886.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!