首页 > 其他 > 详细

leetcode 62、Unique Paths

时间:2019-03-06 14:32:20      阅读:151      评论:0      收藏:0      [点我收藏+]

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 7 x 3 grid. How many possible unique paths are there?

Note: m and n will be at most 100.

Example 1:

Input: m = 3, n = 2
Output: 3
Explanation:
From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Right -> Down
2. Right -> Down -> Right
3. Down -> Right -> Right

Example 2:

Input: m = 7, n = 3
Output: 28

题目大意:

从m乘n矩阵左上角走到右下角,每一步只能向右或向下,求共有多少条不同路径。

递归解决:

 1 class Solution {
 2 public:
 3     vector<vector<int>> v;
 4     
 5     int solve(int m, int n) {//从(m, n)到(1, 1)有多少条路径
 6         if (m == 1 || n == 1)
 7             return 1;
 8         if (v[m][n] >= 0)
 9             return v[m][n];
10         v[m][n] = solve(m - 1, n) + solve(m, n - 1);
11         return v[m][n];
12     }
13     
14     int uniquePaths(int m, int n) {
15         if (m == 0 || n == 0)
16             return 0;
17         if (m == 1 || n == 1)
18             return 1;
19         v.resize(m + 1, vector<int>(n + 1, -1));
20         return solve(m - 1, n) + solve(m, n - 1);
21     }
22 };

 迭代:

 1 class Solution {
 2 public:
 3     
 4     int uniquePaths(int m, int n) {
 5         if (m == 0 || n == 0)
 6             return 0;
 7         vector<vector<int>> v(m, vector<int>(n));
 8         int i, j;
 9         for (i = 0; i < m; i++) {
10             for (j = 0; j < n; j++) {
11                 if (i == 0 || j == 0)
12                     v[i][j] = 1;
13                 else
14                     v[i][j] = v[i - 1][j] + v[i][j - 1];
15             }
16         }
17         return v[m - 1][n - 1];
18     }
19 };

 

leetcode 62、Unique Paths

原文:https://www.cnblogs.com/lxc1910/p/10482789.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!