zoukankan      html  css  js  c++  java
  • LeetCode题解——Unique Path(DP与优化)

    题目: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?

    题意:在m*n的网格中,从左下角一步步走到右上角,有多少种可能的走法(每次只能横或竖移动一步)

        在第一象限的话,也就是每次走一步从(0,0)走到(m,n)有多少种走法

    思路:考虑这是一个递推的问题,根据DP思想,有递推公式

    我的代码比较短,因为memset只能置0或者-1,可以把数组置为-1,然后和取负就是所求结果了。

    class Solution {  
    public:  
        int uniquePaths(int m, int n) {  
            // Start typing your C/C++ solution below  
            // DO NOT write int main() function  
            int f[m][n];  
            memset(f, -1, sizeof(int) * m * n);  //数组全部置-1
            for (int i = 1; i < m; i++) {            //求和
                for (int j = 1; j < n; j++) {  
                    f[i][j] = f[i - 1][j] + f[i][j - 1];  
                }  
            }  
            return -f[m - 1][n - 1];  //取负
        }  
    };       

    时间复杂度O(m*n),那么可不可以继续优化呢?

    上面采用的是二维数组,现在可以用一位数组取代之,则

    Fn=Fn-1+Fn;

    class Solution {
    public:
        int uniquePaths(int m, int n) {
            vector<int> vec(n, 1);
            for(int i=1; i<m; ++i){
                for(int j=1; j<n; ++j){
                    vec[j]+=vec[j-1];
                }
            }
            return vec[n-1];
        }
    };
  • 相关阅读:
    C#Webform 控件
    C#Webform
    MVC Razor 语法
    input file 添加
    ajax
    jquery动画
    jquery选择器,事件 dom操作
    linq 复杂查询
    webform(linq增删改查)
    asp.net内置对象
  • 原文地址:https://www.cnblogs.com/134feilei/p/3819940.html
Copyright © 2011-2022 走看看