首页 > 其他 > 详细

Unique Paths

时间:2017-05-25 09:24:37      阅读:190      评论:0      收藏:0      [点我收藏+]
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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!