Unique Paths

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. 

posted on 2017-05-25 06:53  codingEskimo  阅读(68)  评论(0编辑  收藏  举报

导航