๋ฌธ์ ๋งํฌ
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 |