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 };
  • 相关阅读:
    拿webshell方法汇总
    Linux跑脚本用sh和./有什么区别?
    安全测试工具
    浏览器被劫持网上优秀的修复方法
    Linux 逻辑卷扩容
    sed替换文本
    mysql 用户创建,授权
    编程之约定
    java 对象成员变量初始化顺序
    java 静态成员初始化顺序
  • 原文地址:https://www.cnblogs.com/CheeseZH/p/5006718.html
Copyright © 2011-2022 走看看