zoukankan      html  css  js  c++  java
  • [Leetcode] 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.

     题意:从左上角到右下角,总共有多少条路径。

    思路:动态规划。维护一个二维数组,dp[i][j]代表到达第i 行j列有几种方法。转移方程为:dp[i][j]=dp[i-1][j]+dp[i][j-1]。如图:

    代码如下:

     1 class Solution {
     2 public:
     3     int uniquePaths(int m, int n) 
     4     {
     5         if(m=0||n=0)    return 1;
     6         int dp[m][n];
     7         dp[0][0]=1;
     8 
     9         for(int i=1;i<m;++i)
    10             dp[i][0]=1;
    11         for(int i=1;i<n;++i)  
    12             dp[0][i]=1;
    13 
    14         for(int i=1;i<m;++i)
    15         {
    16             for(int j=1;j<n;++j)
    17             {
    18                 dp[i][j]=dp[i-1][j]+dp[i][j-1];
    19             }
    20         }  
    21         return dp[m-1][n-1];
    22     }
    23 };

    同种思路:另一种方法,使用滚动数组,利用一个一维数组实现上述过程,改动的思路是,二维数组中的dp[i][j]的值是表中的前一个和上一个,可以看成一维数组中的,前一个和其本身。

     1 class Solution {
     2 public:
     3     int uniquePaths(int m, int n) 
     4     {
     5         vector<int> dp(n,1);
     6         for(int i=1;i<m;++i)
     7         {
     8             for(int j=1;j<n;++j)
     9             {
    10                 dp[j]+=dp[j-1];
    11             }
    12         }
    13         return dp[n-1];
    14     }
    15 };
  • 相关阅读:
    PHP里json_encode()与json_decod()区别
    数组进行排序
    tp5利用自带上传类实现单个文件与多文件上传
    mkdir() Permission denied 报错问题
    如何快速熟悉新项目的代码?
    Tp5自定义路径写入日志
    spring解决循环依赖
    spring注解的使用
    ssm的整合
    编程知识总结
  • 原文地址:https://www.cnblogs.com/love-yh/p/7121533.html
Copyright © 2011-2022 走看看