119. 杨辉三角 II

125 阅读1分钟

题目介绍

力扣119题:leetcode-cn.com/problems/pa…

image.png

动态规划

改题目的解题思路跟[118. 杨辉三角]类似,无非就是返回结果的时候取出最后一行的值即可。

代码如下:

class Solution {
    public List<Integer> getRow(int rowIndex) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        int[][] dp = new int[rowIndex+1][rowIndex+1];
        dp[0][0] = 1;
        for (int i = 1; i < rowIndex + 1; i++) {
            for (int j = 0; j <= i; j++) {
                if(j == 0) {
                    //第一列和最后一列的值都是1
                    dp[i][j] = 1;
                }else {
                    dp[i][j] = dp[i-1][j-1] + dp[i-1][j];
                }
            }
        }

        //将二维数组转为List<List<Integer>>类型
        for (int i = 0; i < dp.length; i++) {
            List<Integer> tmp = new ArrayList<>();
            for (int j = 0; j < dp.length; j++) {
                if(dp[i][j] == 0) {
                    //走到本行的末尾了
                    break;
                }
                tmp.add(dp[i][j]);
            }
            result.add(new ArrayList<>(tmp));
        }
        //返回最后一行的值即可
        return result.get(result.size() -1);
    }
}