LeetCode Pascal's Triangle (JavaScript)

2025. 12. 9. 17:50·코딩테스트/LeetCode

링크 : https://leetcode.com/problems/pascals-triangle/description/

문제 설명

더보기

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

문제 풀이

1. numRows + 1 * numRows + 1만큼의 배열을 만들어 각 행을 돌면서 계산

-> arr[y][x] = arr[y - 1][x] + arr[y - 1][x - 1]로 계산

-> 일단 numRows + 1만큼의 2차원 배열을 생성하고 n^2의 시간 복잡도로 해결이 가능.

/**
 * @param {number} numRows
 * @return {number[][]}
 */
var generate = function(numRows) {
    let arr = Array.from({length: numRows + 1}, () => Array.from({length: numRows + 1}, () => 0));

    arr[1][1] = 1;

    for (let i = 2; i <= numRows; i++) {
        for (let j = 1; j <= numRows; j++) {
            arr[i][j] = arr[i - 1][j] + arr[i - 1][j - 1];
        }
    }

    return arr.slice(1).map(a => a.filter(Boolean));
};

2. 위의 알고리즘을 좀 더 효율적으로 해결

tmp는 다음 행을 계산할 데이터, 이전 행 값(answer[answer.length - 1])을 기준으로 계산 (앞 뒤로 0이 필요)

e.g. 2번째 행 계산인 경우

tmp = [0, 1, 0] -> 다음 행은 [1, 1]이 나와야 함

즉, tmp의 길이 - 1만큼 반복하면서 (위의 예시에서는 2번) j번째 + j + 1번째를 더해주면 됨.

/**
 * @param {number} numRows
 * @return {number[][]}
 */
var generate = function(numRows) {
    const answer = [[1]];

    for (let i = 0; i < numRows - 1; i++) {
        const tmp = [0, ...answer[answer.length - 1], 0];
        const item = [];

        for (let j = 0; j < tmp.length - 1; j++) {
            item.push(tmp[j] + tmp[j + 1]);
        }

        answer.push(item);
    }

    return answer;
};

결론

배열을 생성해서 쉽게 해결할 수 있지만 좀 더 효율적인 방법을 생각해보는 것이 포인트인 것 같다.

'코딩테스트 > LeetCode' 카테고리의 다른 글

LeetCode Minimum Path Sum (JavaScript)  (0) 2025.12.11
LeetCode Unique Paths (JavaScript)  (0) 2025.12.10
LeetCode Remove Duplicates from Sorted List (JavaScript)  (0) 2025.12.09
LeetCode Climbing Stairs (JavaScript)  (0) 2025.12.08
LeetCode Sqrt(x) (JavaScript)  (1) 2025.12.08
'코딩테스트/LeetCode' 카테고리의 다른 글
  • LeetCode Minimum Path Sum (JavaScript)
  • LeetCode Unique Paths (JavaScript)
  • LeetCode Remove Duplicates from Sorted List (JavaScript)
  • LeetCode Climbing Stairs (JavaScript)
의현
의현
개발하는 하루
  • 의현
    UIHYEON
    의현
  • 링크

    • 김의현 포트폴리오
    • GitHub
    • LinkedIn
  • 전체
    오늘
    어제
    • 분류 전체보기 (215) N
      • 프론트엔드 (65) N
        • JavaScript (52) N
        • HTML (3)
        • React (7)
        • CSS (2)
        • CS (1)
      • 프로젝트 (19)
        • Portfolio 사이트 개발 (19)
      • 코딩테스트 (128) N
        • Binary Search (2)
        • bfs (Breadth-first s.. (4)
        • dfs (Deapth-first se.. (1)
        • Greedy (1)
        • Dynamic Programming (1)
        • two pointer (4)
        • 구현 (2)
        • LIS(Longest Increasi.. (0)
        • 문자열 (3)
        • 자료구조 (6)
        • 비트마스크 (2)
        • 수학 (2)
        • 프로그래머스 (61)
        • LeetCode (39) N
  • 인기 글

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
의현
LeetCode Pascal's Triangle (JavaScript)
상단으로

티스토리툴바