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

Leetcode: Unique Paths

时间:2015-04-10 01:22:35      阅读:239      评论:0      收藏:0      [点我收藏+]

标签:leetcode   动态优化   

题目:

A robot is located at the top-left corner of a m x n grid (marked ‘Start‘ in the diagram below).

The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked ‘Finish‘ in the diagram below).

How many possible unique paths are there?

技术分享

Above is a 3 x 7 grid. How many possible unique paths are there?

Note: m and n will be at most 100.




思路分析:

又是动态规划问题。


开一个f[m][n]的数组,数组元素初始化为1,递推公式f[i][j] = f[i-1][j] + f[i][j-1],空间时间复杂度O(m*n)。

(可以将f[m][n]理解成为从f[0][0]到达f[m][n]的路径个数。那很自然的就会f[i][j] = f[i-1][j] + f[i][j-1]。有感觉递推公式还不是能很好想出来的,继续加强训练吧!)



C++参考代码:

class Solution
{
public:
    int uniquePaths(int m, int n)
    {
        //将vector中的元素初始化为1
        vector<vector<int>> v(m, vector<int>(n, 1));
        for (int i = 1; i < m; ++i)
        {
            for (int j = 1; j < n; ++j)
            {
                v[i][j] = v[i - 1][j] + v[i][j - 1];
            }
        }
        return v[m - 1][n - 1];
    }
};

代码还可以进一步优化。

由C(n,k) = C(n-1,k) + C(n-1,k-1);
对应于杨辉三角
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
………………

所以利用杨辉三角,开一个f[n]的数组,数组元素初始化为1,递推公式f[i]+=f[i-1],空间时间复杂度O(n)。

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


Leetcode: Unique Paths

标签:leetcode   动态优化   

原文地址:http://blog.csdn.net/theonegis/article/details/44968639

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