现在的位置: 首页 > 综合 > 正文

LeetCode——Unique Paths

2014年11月09日 ⁄ 综合 ⁄ 共 783字 ⁄ 字号 评论关闭

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?

Note: m and n will
be at most 100.

»
Solve this problem

由于只能往下或者往右走,因此(i, j)只会由(i - 1, j)或者(i, j - 1)到达。

假设,到达(i - 1, j)有f[i - 1, j]种走法,到达(i, j - 1)有f[i, j - 1]种走法,那么到达(i, j)有f[i, j] = f[i - 1, j] + f[i, j - 1]中走法。

class Solution {
public:
    int uniquePaths(int m, int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int f[m][n];
        memset(f, 0, sizeof(int) * m * n);
        for (int i = 0; i < m; i++) {
            f[i][0] = 1;
        }
        for (int j = 0; j < n; j++) {
            f[0][j] = 1;
        }
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                f[i][j] = f[i - 1][j] + f[i][j - 1];
            }
        }
        return f[m - 1][n - 1];
    }
};

抱歉!评论已关闭.