Unique Paths Leetcode

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.

这道题感觉是个经典的dp题目。dp就是建一个二维数组然后看看每个步骤结果应该是怎样的。

public class Solution {
    public int uniquePaths(int m, int n) {
        if (m <= 0 || n <= 0) {
            return 0;
        }
        // if (m == 1 || n == 1) {
        //     return 1;
        // }
        int[][] path = new int[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (i == 0 && j != 0) {
                    path[i][j] = 1;
                } else if (i != 0 && j == 0) {
                    path[i][j] = 1;
                } else if (i != 0 && j != 0) {
                    path[i][j] = path[i - 1][j] + path[i][j - 1];
                } else {
                    path[i][j] = 1;
                }
            }
        }
        return path[m - 1][n - 1];
    }
}

这道题需要注意的是有的时候数组会变成一维的,这个时候总数只有一个,可以通过一开始判断返回,也可以把path[0][0]赋值为1来包含长度为2,维度为1的情况。

这道题还有数学解法。。。在此先不深究了,到时候有时间再回顾吧。。。

posted @ 2017-03-02 04:37  璨璨要好好学习  阅读(111)  评论(0编辑  收藏  举报