leetcode_c++: Unique Paths(062)

原创 2016年06月01日 00:50:50

题目

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?

Above is a 3 x 7 grid. How many possible unique paths are there?


算法

DP
复杂度:O(nm)

  1. 机器人要到(i,j)点,可以选择(i-1,j)和(i,j-1)
    到(i,j)的唯一路径数
    dp[i][j] = dp[i-1][j] + dp[i][j-1]
    dp[i][j] 是从(0,0) 到(i,j)的唯一路径

  2. 网格最上边和最左边,则只能从起点走直线,dp[0][j]=dp[i][0]=1

  3. 计算方向从上到下,从左到右,滚动数组

class Solution {
public:
    int uniquePaths(int m, int n) {
        int dp[m][n];

        // 初始化dp,m*1全是1的情况
        for(int i=0;i<m;i++)
            dp[i][0]=1;

        // 初始化dp,1*n全是1的情况
        for(int j=0;j<n;j++){
            dp[0][j]=1;
        }

        for(int i=1;i<m;i++){
            for(int j=1;j<n;j++)
                dp[i][j]=dp[i-1][j]+dp[i][j-1];
        }

        return dp[m-1][n-1];
    }
};
版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

【LeetCode-面试算法经典-Java实现】【062-Unique Paths(唯一路径)】

【062-Unique Paths(唯一路径)】【LeetCode-面试算法经典-Java实现】【所有题目目录索引】原题  A robot is located at the top-left cor...

LeetCode062 Unique Paths

详细见:leetcode.com/problems/unique-paths Java Solution: github package leetcode; import java....
  • zxwtry
  • zxwtry
  • 2017年04月13日 21:55
  • 84

LeetCode: Unique Paths II [062]

【题目】 Follow up for "Unique Paths": Now consider if some obstacles are added to the grids. How man...

[C++]LeetCode: 56 Unique Paths

题目: A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram belo...

LeetCode 63 — Unique Paths II(C++ Java Python)

题目:http://oj.leetcode.com/problems/unique-paths-ii/ Follow up for "Unique Paths": Now consider if so...

Unique Paths -leetcode

这样一道题目: A robot is located at the top-left corner of a m x n grid (marked ‘Start’ in the diagram b...

LeetCode || Unique Paths

A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). Th...

leetcode--unique_paths

leetcode–unique_paths题意:给定一个m×n的网格,一个机器人从网格最左上角到网格最右下角,它只能往右或者往下走,总共有多少种唯一的路径。                下图为一个...

leetcode 62. Unique Paths-唯一路径|动态规划

Total Accepted: 80566 Total Submissions: 225855 Difficulty: Medium A robot is located at the top-...

[LeetCode]--63. Unique Paths II

Follow up for “Unique Paths”:Now consider if some obstacles are added to the grids. How many unique ...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:leetcode_c++: Unique Paths(062)
举报原因:
原因补充:

(最多只允许输入30个字)