[leetcode]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?

Above is a 3 x 7 grid. How many possible unique paths are there?

Note: m and n will be at most 100.

解题思路:简单分治思想。定义一个m*n的二维数组matrix,将matrix[i][0]和matrix[0][j]的值设定为1(i的取值为[0,m-1],j的取值范围为[0,n-1]),接下来matrix[i][j]的值就是matrix[i-1][j]与matrix[i][j-1]的和,最后输出matrix[m-1][n-1]即可。

代码如下:

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

题目链接:https://leetcode.com/problems/unique-paths/

你可能感兴趣的:(LeetCode)