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

Unique Paths

时间:2017-05-25 10:06:28      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:value   poi   rom   ==   one   ret   []   tom   blog   

public class Solution {
    /**
     * @param n, m: positive integer (1 <= n ,m <= 100)
     * @return an integer
     */
    public int uniquePaths(int m, int n) {
        if (m <= 0 || n <= 0) {
            return 1;
        }
        
        if (m == 1 || n == 1) {
            return 1;
        }
        // write your code here 
        // initialize
        //f[x][y]: unique path number from (0,0) to (x, y)
        int[][] f = new int[m][n];
        //inital the first value
        f[0][0] = 0;
        //initial the top
        for (int i = 1; i < n; i++) {
            f[0][i] = 1; //only one path could reach those points
        }
        //initial the left
        for (int i = 1; i < m; i++) {
            f[i][0] = 1;
        }
        
        //from top to bottom, from left to right
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                f[i][j] = f[i - 1][j] + f[i][j - 1]; 
            }
        }
        
        return f[m - 1][n - 1];
    }
}

Actually it can initial f[0][0] to 1, so that it can avoid a lot of coner checking. 

Unique Paths

标签:value   poi   rom   ==   one   ret   []   tom   blog   

原文地址:http://www.cnblogs.com/codingEskimo/p/6901824.html

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