leetcode(62): Unique Paths

leetcode(62): Unique Paths

题目

一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为“Start” )。

机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。

问总共有多少条不同的路径?

leetcode(62): Unique Paths

例如,上图是一个7 x 3 的网格。有多少可能的路径?

说明:m 和 n 的值均不超过 100。
示例 1:

输入: m = 3, n = 2
输出: 3
解释:
从左上角开始,总共有 3 条路径可以到达右下角。

  1. 向右 -> 向右 -> 向下
  2. 向右 -> 向下 -> 向右
  3. 向下 -> 向右 -> 向右
    示例 2:

输入: m = 7, n = 3
输出: 28

  1. Unique Paths
    Medium

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

思路

题解
这道题拿到题目我觉得大家的第一反应都是这应该是递归的题目,因为我们可以转化为子问题,但是这样暴力肯定会超时,就不用尝试了。其实在该题递归的方法就是从上面到下面不断的去尝试,如果我们能记住之前的结果,就对我们下一步有帮助,所以想到了DP的方法。
格子中的数字代表当前的方法.

初始状态
leetcode(62): Unique Paths

当前这个状态只和左边和上边的格子有关系.
leetcode(62): Unique Paths

依次求解
leetcode(62): Unique Paths

于是我们可以得到状态转移方程:
ways[i][j] = ways[i-1][j] + ways[i][j-1];

代码

class Solution {
public:
	int uniquePaths(int m, int n) {    
        vector<int> paths(n, 1);
		
		for (int i = 1; i < m; i++) {
			for (int j = 1; j < n; j++) {
				paths[j] = paths[j] + paths[j - 1];
				
			}

		}
		return paths[n-1];
	}

};