๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

์ฝ”๋”ฉํ…Œ์ŠคํŠธ/LeetCode

[LeetCode] Pascals Triangle

๋ฌธ์ œ๋งํฌ

 

Pascal's Triangle - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

์œ„์™€ ๊ฐ™์€ ๊ทœ์น™์œผ๋กœ ์ง„ํ–‰๋˜๋Š” pascals triangle์„ 2์ฐจ์› ๋ฐฐ์—ด๋กœ ๋‚˜ํƒ€๋‚ด๋Š” ๋ฌธ์ œ์ด๋‹ค.
numRows๋กœ ์‚ผ๊ฐํ˜•์˜ ํฌ๊ธฐ๊ฐ€ ์ฃผ์–ด์ง„๋‹ค.

์ ‘๊ทผ ๋ฐฉ๋ฒ•

2๊ฐ€์ง€ ๊ฒฝ์šฐ๋กœ ๋‚˜๋ˆ„์–ด ํ’€์ดํ•˜์˜€๋‹ค.

1. 1์„ ์ฑ„์›Œ์•ผํ•˜๋Š” ๊ฒฝ์šฐ

2. ์ด์ „์˜ 2๊ฐ€์ง€ ์ˆ˜๋ฅผ ๋”ํ•˜์—ฌ ๋‹ค์Œ ์ˆ˜๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” ๊ฒฝ์šฐ

for(let i = 0; i < numRows; i++){
    for(let j = 0; j <= i; j++){
        if(j === 0 || j === i){
            output[i].push(1)
        }else{
            output[i].push(output[i-1][j-1] + output[i-1][j])
        }
    }
}โ€‹

2์ค‘ for๋ฌธ์„ ์‚ฌ์šฉํ•˜์—ฌ i๋Š” ์‚ผ๊ฐํ˜•์˜ ํ–‰, j๋Š” ์‚ผ๊ฐํ˜•์˜ ์—ด์„ ํ‘œํ˜„ํ•˜์˜€๋‹ค.

1. ๋งŒ์•ฝ ์—ด(j)์ด 0 ๋˜๋Š” ํ•ด๋‹นํ•˜๋Š” ํ–‰(i)๊ณผ ๊ฐ™๋‹ค๋ฉด 1์„ ์ถ”๊ฐ€ํ•œ๋‹ค.

2. ์œ„์˜ ๊ฒฝ์šฐ๊ฐ€ ์•„๋‹ˆ๋ผ๋ฉด ์ด์ „ํ–‰์˜ ์—ด๊ณผ ๊ทธ ์ด์ „ ์—ด์„ ๋”ํ•˜์—ฌ ์ด๋ฒˆํ–‰์˜ ์—ด์„ ํ‘œํ˜„ํ•œ๋‹ค.

 

/**
 * @param {number} numRows
 * @return {number[][]}
 */
var generate = function(numRows) {
    const output = Array.from({length : numRows}, () => []);
    
    for(let i = 0; i < numRows; i++){
        for(let j = 0; j <= i; j++){
            if(j === 0 || j === i){
                output[i].push(1)
            }else{
                output[i].push(output[i-1][j-1] + output[i-1][j])
            }
        }
    }
    
    return output
};

'์ฝ”๋”ฉํ…Œ์ŠคํŠธ > LeetCode' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[LeetCode] Search A 2d Matrix II  (0) 2022.07.24
[LeetCode] Number Of Matching Subsequences  (0) 2022.07.20
[LeetCode] Single Number II  (0) 2022.07.15
[LeetCode] Matchsticks To Square  (0) 2022.07.12
[LeetCode] Combination Sum  (0) 2022.07.11