码迷,mamicode.com
首页 > 其他好文 > 详细

Jan 19 - Unique Paths; Array; DP;

时间:2016-01-20 09:59:46      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:

first of all, we‘re goin to create a 2D array(int[][] grid) to store the number of paths to each position. we get the minimum value of m and n, mark it as min, then look through the row and column of grid[i][i] in each loop, when i == 0, we know we are looking through the toppest row and leftmost column in the array, and set the value of each element in the row and column to be 1. (This is because we can only go to the position in one unique path.) When 0<i<min, the value of the element is grid[i][j] = grid[i-1][j] + grid[i][j-1]; When the loop ends, we will finally get the value of grid[m-1][n-1], which the number of unique paths that we want to obtain.

Code:

public class Solution {
    public int uniquePaths(int m, int n) {
        int[][] grid = new int[m][n]; 
        if(m == 0 && n == 0){
            grid[m][n] = 1;
            return grid[m][n];
        }
        int min = m < n? m:n;
        int i = 0;
        for(; i < min; i++){
            if(i == 0){
                for(int j = 0; j < m; j++) grid[j][0] = 1;
                for(int j = 0; j < n; j++) grid[0][j] = 1;
            }
            else{
                for(int j = i; j < m; j++) grid[j][i] = grid[j-1][i] + grid[j][i-1];
                for(int j = i; j < n; j++) grid[i][j] = grid[i-1][j] + grid[i][j-1];
            }
        }
        return grid[m-1][n-1];
    }
    
}

  

Jan 19 - Unique Paths; Array; DP;

标签:

原文地址:http://www.cnblogs.com/5683yue/p/5144044.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!