• 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];
        }
    };
    
  • 相关阅读:
    Windows系统结构
    Windows系统基本概念
    基本NT式驱动代码结构
    数据切割
    虚函数
    基类和派生类:谈继承
    jQuery简单的上拉加载
    检测是否为数组
    倒计时案例分析
    获得总的毫秒数
  • 原文地址:https://www.cnblogs.com/lengender-12/p/6895838.html
Copyright © 2020-2023  润新知