25.杨辉三角

/*给定一个非负整数 numRows,生成「杨辉三角」的前 numRows 行。

在「杨辉三角」中,每个数是它左上方和右上方的数的和。
思路:
把杨辉三角转化为一维数组就是:
[1]
[1,1]
[1,2,1]
[1,3,3,1]
.......

返回结果为全集,把状态方程设置成二维数组即可。
状态方程: dp[i][j]=dp[i - 1][j] + dp[i - 1]j - 1;常量值为:dp[i][0]=1,dp[i][i]=1
*/
class Solution {
      public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> result = new ArrayList<>();
        int[][] dp = new int[numRows][numRows];
        dp[0][0] = 1;
        result.add(new ArrayList<Integer>(){{ add(dp[0][0]);}});
        if (numRows == 1) {
            return result;
        }

        for (int i = 1; i < numRows; i++) {
            List<Integer> num = new ArrayList<>();
            dp[i][0] = 1;
            num.add(dp[i][0]);
            for (int j = 1; j < i; j++) {
                dp[i][j] = dp[i - 1][j] + dp[i - 1][j - 1];
                num.add(dp[i][j]);
            }
            dp[i][i] = 1;
            num.add(dp[i][i]);
            result.add(num);
        }
        return result;
    }

}

 

posted @ 2022-03-12 08:41  随遇而安==  阅读(44)  评论(0编辑  收藏  举报