Unique path

题目:

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?

 

解法一:自己写的,比较诡异

 1     public int uniquePaths(int m, int n) 
 2     {
 3         int [][] grids = new int [m+1][n+1];
 4         grids[m][n-1]=1;
 5         for (int i=m-1;i>=0;i--)
 6         {
 7             for (int j=n-1;j>=0;j--)
 8             {
 9                 grids[i][j]=grids[i+1][j]+grids[i][j+1];
10         
11                 
12             }
13         }
14         return grids[0][0];
15     }

 

解法二:九章算法,好理解

 1 public class Solution {
 2     public int uniquePaths(int m, int n) {
 3         if (m == 0 || n == 0) {
 4             return 0;
 5         }
 6         
 7         int[][] sum = new int[m][n];
 8         for (int i = 0; i < m; i++) {
 9             sum[i][0] = 1;
10         }
11         for (int i = 0; i < n; i++) {
12             sum[0][i] = 1;
13         }
14         for (int i = 1; i < m; i++) {
15             for (int j = 1; j < n; j++) {
16                 sum[i][j] = sum[i - 1][j] + sum[i][j - 1];
17             }
18         }
19         return sum[m - 1][n - 1];
20     }
21 }

reference:http://www.jiuzhang.com/solutions/unique-paths/

posted @ 2015-09-23 11:26  Hygeia  阅读(228)  评论(0编辑  收藏  举报