zoukankan      html  css  js  c++  java
  • Lintcode: Unique Paths

    C++

    dp

    递推式:dp[i][j] = dp[i-1][j] + dp[i][j-1]

    初值:dp[i][j] = 1,i=0 or j=0

    空间优化:省掉一维

     1 class Solution {
     2 public:
     3     /**
     4      * @param n, m: positive integer (1 <= n ,m <= 100)
     5      * @return an integer
     6      */
     7     int uniquePaths(int m, int n) {
     8         // wirte your code here
     9         vector<vector<int> > dp(m,vector<int>(n));
    10         for (int i = 0; i < m ; ++i) {
    11             for (int j = 0; j < n; ++j) {
    12                 if ( i == 0 ) {
    13                     dp[i][j] = 1;
    14                 } else if ( j == 0 ) {
    15                     dp[i][j] = 1;
    16                 } else {
    17                     dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
    18                 }
    19             }
    20         }
    21         return dp[m - 1][n - 1];
    22     }
    23 };

    空间优化

     1 class Solution {
     2 public:
     3     /**
     4      * @param n, m: positive integer (1 <= n ,m <= 100)
     5      * @return an integer
     6      */
     7     int uniquePaths(int m, int n) {
     8         // wirte your code here
     9         // vector<vector<int> > dp(m,vector<int>(n));
    10         vector<int> dp(n);
    11         for (int i = 0; i < m ; ++i) {
    12             for (int j = 0; j < n; ++j) {
    13                 if ( i == 0 ) {
    14                     dp[j] = 1;
    15                 } else if ( j == 0 ) {
    16                     dp[j] = 1;
    17                 } else {
    18                     dp[j] = dp[j] + dp[j - 1];
    19                 }
    20             }
    21         }
    22         return dp[n - 1];
    23     }
    24 };
  • 相关阅读:
    国际区号选取组件
    python和js执行字符串函数
    mysql存储过程循环遍历某个表以及事件
    mysql创建远程用户
    ubuntu改文件夹权限
    mysql最大连接数
    MSYS
    Eclipse Java 可视化插件
    你不知道的继承
    vue3.x
  • 原文地址:https://www.cnblogs.com/CheeseZH/p/5006718.html
Copyright © 2011-2022 走看看