[leetcode #118] Pascal's Triangle

Seongyeol Shin·2022년 7월 19일
0

leetcode

목록 보기
194/196
post-thumbnail

Problem

Given an integer numRows, return the first numRows of Pascal's triangle.

In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:

Example 1:

Input: numRows = 5
Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]

Example 2:

Input: numRows = 1
Output: [[1]]

Constraints:

· 1 <= numRows <= 30

Idea

파스칼 삼각형을 구해 리턴하는 문제다.

파스칼 삼각형의 현재 row 값을 구할 때 이전 row 값을 참조하는 방식은 다음과 같다.

current[i] = previous[i-1] + previouse[i]

첫 줄에 1을 넣은 뒤 나머지 줄은 위 공식을 따라 값을 정하고, 처음과 끝 값은 1로 정하면 된다.

Solution

class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> res = new ArrayList<>();
        res.add(List.of(1));

        for (int i=1; i <= numRows; i++) {
            List<Integer> row = new ArrayList<>();
            List<Integer> prev = res.get(i-1);
            for (int j=0; j < i; j++) {
                if (j == 0 || j == i-1) {
                    row.add(1);
                } else {
                    row.add(prev.get(j-1) + prev.get(j));
                }
            }
            res.add(row);
        }

        return res.subList(1, res.size());
    }
}

Reference

https://leetcode.com/problems/pascals-triangle/

profile
서버개발자 토모입니다

0개의 댓글