Unique Paths

Unique Paths

A.题意

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?

大致的题意是机器人要从左上角走到右下角,机器人只能走右边和下边,问你一共有多少种方法。

B.思路

这道题目其实就是排列组合问题不过考虑到可能数字会很大溢出这里我们可以采用动态规划的思路,机器人只能往右和往下走,故到达每一个格子的方法数为左边一个格子方法数加上边一个格子方法数,所以递归方程为

grid[i][j] = grid[i - 1][j] + grid[i][j - 1];

C.代码实现

class Solution {
public:
    int uniquePaths(int m, int n) {
        if (m == 1 || n == 1)
        {
            return 1;
        }
        vector<vector<int> > grid(m, vector<int>(n, 0));
        for (int i = 1;i < m;i++)
        {
            grid[i][0] = 1;
        }
        for (int i = 1;i < n;i++)
        {
            grid[0][i] = 1;
        }
        for (int i = 1;i < m;i++)
        {
            for (int j = 1;j < n;j++)
            {
                grid[i][j] = grid[i - 1][j] + grid[i][j - 1];
            }
        }
        return grid[m - 1][n - 1];
    }
};
点赞