Leetcode - 119. 杨辉三角 II

解题思路参考代码中的注释:
class Solution {
    public List<Integer> getRow(int rowIndex) {
        
        // 数组arr代表杨辉三角的一行,第rowIndex行总共有rowIndex + 1个数字
        // 变量length代表数组arr中的实际长度
        int[] arr = new int[rowIndex + 1];
        int length = 0;

        // 根据杨辉三角的规律进行迭代,直到数组实际长度达到数组的长度
        while (length < arr.length) {
            for (int i = length - 1; i > 0; i--) {
                arr[i] += arr[i - 1];
            }
            arr[length++] = 1;
        }
        return toList(arr);
    }

    private static List<Integer> toList(int[] arr) {
        List<Integer> ret = new ArrayList<>(arr.length);
        for (int i : arr) {
            ret.add(i);
        }
        return ret;
    }
}
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务