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?

推荐方法:DP矩阵做法其实还可以节省一维:2D矩阵变成一维数组DP:

 1 public int uniquePaths(int m, int n) {

 2     if(m<=0 || n<=0)

 3         return 0;

 4     int[] res = new int[n];

 5     res[0] = 1;

 6     for(int i=0;i<m;i++)

 7     {

 8         for(int j=1;j<n;j++)

 9         {

10            res[j] += res[j-1];

11         }

12     }

13     return res[n-1];

14 }

一维DP方法2:

 1 public class Solution {

 2     public int uniquePaths(int m, int n) {

 3         if (m == 0 || n == 0) return 0;

 4         int[] res = new int[n];

 5         for (int k=0; k<n; k++) {

 6             res[k] = 1;

 7         }

 8         for (int i=1; i<m; i++) {

 9             for (int j=1; j<n; j++) {

10                 res[j] = res[j-1] + res[j];

11             }

12         }

13         return res[n-1];

14     }

15 }

 

你可能感兴趣的:(LeetCode)