FTPrep, 62 Unique Paths

来源:互联网 发布:2014网络作家富豪榜 编辑:程序博客网 时间:2024/06/06 11:02

很简单的一道DP题目,而且只用了一个 一维数组 来记录左方和上方的元素,果然看透了本质,感觉是那么通透,解题是那么爽。


class Solution {    public int uniquePaths(int m, int n) {        if(m==0 || n==0) return 0;        int[] record = new int[n];        record[0]=1;        for(int i=0; i<m; i++){            for(int j=1; j<n; j++){  // I changed j=0 to j=1, because of the following tranfer function and                 //the fact that record[0] will always be 1;                record[j] += record[j-1];            }        }        return record[n-1];    }}

当然,可以用 另一种思路来解题,转化一下问题,这就是在 (n-1)+(m-1) 步里选出 n 步,作为纵向移动的步数,那就用组合的公式计算就可以

比如 9*8*7 / 1*2*3 就是一个 8 x 3 的格子的结果。

但是这么做的问题就是,当m和n很大时,就会越界,因为这里是得到一个很大的数,再用除法,凡是这种除数的,都要考虑到越界。当然你可以用(double)和(int) 进行强行类型转化。