zoukankan      html  css  js  c++  java
  • Leetcode:62. Unique Paths

    Description

    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?

    思路

    • 明显的动态规划嘛,用一个二维数组记录状态,dp[i][j]表示从(0,0)到(i,j)的路径数
    • dp[i][j] = dp[i][j-1] + dp[i-1][j]
    • 可以把二维数组降到一维

    代码

    • 二维数组
    class Solution {
    public:
        int uniquePaths(int m, int n) {
            vector<vector<int>> flag(m + 1, vector<int>(n + 1, 0));
           
            for(int i = 1; i <= m; ++i)
                flag[i][1] = 1;
            for(int j = 1; j <= n; ++j)
                flag[1][j] = 1;
                
            for(int i = 2; i <= m; ++i){
                for(int j = 2; j <= n; ++j)
                    flag[i][j] = flag[i][j - 1] + flag[i - 1][j];
            }
            
            return flag[m][n];
        }
    };
    
    • 一维数组
    class Solution {
    public:
        int uniquePaths(int m, int n) {
            vector<int> flag(n + 1, 0);
           
            for(int i = 1; i <= n; ++i)
                flag[i] = 1;
            
            int before = 1;
            for(int i = 2; i <= m; ++i){
                before = 1;
                for(int j = 2; j <= n; ++j){
                    flag[j] = flag[j] + before;
                    before = flag[j];
                }
            }
            
            return flag[n];
        }
    };
    
  • 相关阅读:
    Flutter 导航栏上添加搜索按钮
    tabController保活
    nav 选项卡
    flutter 毛玻璃
    [题解]CodeForces878 D
    [题解]CodeForces878C Tournament
    [题解]NOIP2012
    bzoj1070题解
    bzoj1061题解
    bzoj1059题解
  • 原文地址:https://www.cnblogs.com/lengender-12/p/6895838.html
Copyright © 2011-2022 走看看