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 };
  • 相关阅读:
    增量学习中的自我训练
    半监督学习和直推学习的区别
    LeetCode: Word Break
    LeetCode: Linked List Cycle
    LeetCode: Reorder List
    LeetCode: Binary Tree Traversal
    LeetCode: LRU Cache
    LeetCode: Insertion Sort List
    LeetCode: Sort List
    LeetCode: Max Points on a Line
  • 原文地址:https://www.cnblogs.com/CheeseZH/p/5006718.html
Copyright © 2011-2022 走看看