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.

    见代码。

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

    第二遍做的时候果然有新收获,感觉Leetcode刷再多遍都不嫌多,每一次都会有新的收获。下面为第二次刷的时候的代码,我们完全用不着m*n的空间,其实只要m跟n相对较短的那个长度的空间就好了。下面是用了O(n)空间的代码。

     1 class Solution {
     2 public:
     3     int uniquePaths(int m, int n) {
     4         if (m == 0 || n == 0) return 0;
     5         vector<int> dp(n, 1);
     6         for (int i = 1; i < m; ++i) {
     7             for (int j = 1; j < n; ++j) {
     8                 dp[j] += dp[j-1];
     9             }
    10         }
    11         return dp[n-1];
    12     }
    13 };
  • 相关阅读:
    Jmeter参数化-用户定义的变量
    Jmeter进行文件下载
    Jmeter进行文件上传
    Jmeter进行HTTP接口测试
    Jmeter元件作用域及执行顺序
    activiti 汉化
    Spring boot web app项目
    spring boot整合activiti rest api详细教程
    Spring Boot自动配置原理
    spring bean注解使用详解
  • 原文地址:https://www.cnblogs.com/easonliu/p/3636670.html
Copyright © 2011-2022 走看看