zoukankan      html  css  js  c++  java
  • [LeetCode]Unique Paths

    Unique Paths

    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)=f(m-1,n)+f(m,n-1)。

    因为假设往下走一步,就和(m-1,n)一样了,就是f(m-1,n)。

          假设往下右一步,就和(m,n-1)一样了,就是f(m,n-1)。

    还有就是f(m,1)=1 f(1,n)=1,因为所有一行或者一列都只有一种走法。

    递归方法两行搞定,但是里面会有很多的重复计算耗时很多,mn一旦很大,重复计算耗时就会特别大。

    正确做法是从(2,2)开始计算,每个只计算一次。

     1 class Solution {
     2 public:
     3     int uniquePaths(int m, int n) {
     4         vector<vector<int>> f(m+1,vector<int>(n+1,0));
     5         for(int i=1;i<=n;i++) f[1][i]=1;
     6         for(int i=1;i<=m;i++) f[i][1]=1;
     7         for(int i=2;i<=m;i++)
     8         {
     9             for(int j=2;j<=n;j++)
    10             {
    11                 f[i][j]=f[i-1][j]+f[i][j-1];
    12             }
    13         }
    14         return f[m][n];
    15     }
    16 };

    注意这儿的二维vector的初始化为0。

    1 vector<vector<int>> f(m+1,vector<int>(n+1,0));
  • 相关阅读:
    刷题(十五)
    Pycharm按装
    Jmeter
    内存泄露部分检测工具
    Failed to resolve
    图片显示方向不对怎么办
    ScaleType属性
    RobotFramework
    LoadRunner
    Appium
  • 原文地址:https://www.cnblogs.com/Sean-le/p/4795202.html
Copyright © 2011-2022 走看看