算法分析与设计——LeetCode:62. Unique Paths

题目

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?

Note: m and n will be at most 100.

class Solution {
public:
    int uniquePaths(int m, int n) {
    }
};

思路

运用动态规划,对于每一个方格grid[j][i],能到达它的只有它上面和左边的方格grid[j][i-1]和grid[j-1][i],所以它的路径数等于这两个方格路径数之和,而对于整个矩形的上左两条边的方格,路径数都为1,应先赋值。

代码

class Solution {
public:
    int uniquePaths(int m, int n) {
        int grid[100][100];
        for (int i = 0; i < m; i++) {
            grid[0][i] = 1;
        }
        for (int i = 0; i < n; i++) {
            grid[i][0] = 1;
        }
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                grid[j][i] = grid[j-1][i]+grid[j][i-1];
            }
        }
        return grid[n-1][m-1];
    }
};

你可能感兴趣的:(算法leetcode)