Jieunny์˜ ๋ธ”๋กœ๊ทธ

[JS] ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ์ •์ˆ˜ ์‚ผ๊ฐํ˜• ๋ณธ๋ฌธ

Study/Coding Test

[JS] ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ์ •์ˆ˜ ์‚ผ๊ฐํ˜•

Jieunny 2023. 9. 12. 17:17

๐Ÿ“Œ ๋ฌธ์ œ

์œ„์™€ ๊ฐ™์€ ์‚ผ๊ฐํ˜•์˜ ๊ผญ๋Œ€๊ธฐ์—์„œ ๋ฐ”๋‹ฅ๊นŒ์ง€ ์ด์–ด์ง€๋Š” ๊ฒฝ๋กœ ์ค‘, ๊ฑฐ์ณ๊ฐ„ ์ˆซ์ž์˜ ํ•ฉ์ด ๊ฐ€์žฅ ํฐ ๊ฒฝ์šฐ๋ฅผ ์ฐพ์•„๋ณด๋ ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค. ์•„๋ž˜ ์นธ์œผ๋กœ ์ด๋™ํ•  ๋•Œ๋Š” ๋Œ€๊ฐ์„  ๋ฐฉํ–ฅ์œผ๋กœ ํ•œ ์นธ ์˜ค๋ฅธ์ชฝ ๋˜๋Š” ์™ผ์ชฝ์œผ๋กœ๋งŒ ์ด๋™ ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด 3์—์„œ๋Š” ๊ทธ ์•„๋ž˜์นธ์˜ 8 ๋˜๋Š” 1๋กœ๋งŒ ์ด๋™์ด ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค.

์‚ผ๊ฐํ˜•์˜ ์ •๋ณด๊ฐ€ ๋‹ด๊ธด ๋ฐฐ์—ด triangle์ด ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ฃผ์–ด์งˆ ๋•Œ, ๊ฑฐ์ณ๊ฐ„ ์ˆซ์ž์˜ ์ตœ๋Œ“๊ฐ’์„ return ํ•˜๋„๋ก solution ํ•จ์ˆ˜๋ฅผ ์™„์„ฑํ•˜์„ธ์š”.

 

๐Ÿ’ก ์•„์ด๋””์–ด 

1. ์ฒ˜์Œ ์•„์ด๋””์–ด๋Š” ๊ฐˆ ์ˆ˜ ์žˆ๋Š” ๊ฐ’๋“ค์„ ๋จผ์ € ๋ชจ์•„๋‘” ๋‹ค์Œ์— ์ œ์ผ ํฐ ๊ฐ’์œผ๋กœ ๊ฐ€๊ธฐ ์˜€๋Š”๋ฐ ์ƒ๊ฐํ•ด๋ณด๋‹ˆ, ๋ฐฉํ–ฅ์„ฑ์ด ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ๋”ํ•  ์ˆ˜ ์žˆ๋Š” ๊ฐ’์ด ์ œํ•œ๋˜์–ด ์žˆ์–ด์„œ ๊ณ„์† ํฐ๊ฐ’์„ ๋”ํ•ด์ค€๋‹ค๊ณ  ํ•ด์„œ ๊ฒฐ๊ณผ๊ฐ’์ด ์ตœ๋Œ€๊ฐ€ ๋˜๋Š” ๊ฑด ์•„๋‹ˆ์—ˆ๋‹ค.

2. ๊ฐ ์š”์†Œ์—์„œ ๋‚˜์˜ฌ ์ˆ˜ ์žˆ๋Š” ์ œ์ผ ํฐ ํ•ฉ์„ ๊ฐ€์ง„ ๋ฐฐ์—ด์„ ๋งŒ๋“ค๊ณ , ๊ทธ ๋ฐฐ์—ด์—์„œ ๊ฐ€์žฅ ํฐ ๊ฐ’์„ ๋ฝ‘์•„๋‚ด๋ฉด ์ตœ๋Œ€๊ฐ’์„ ์ฐพ์„ ์ˆ˜ ์žˆ๋‹ค.

sumList๋ฅผ ๋งŒ๋“œ๋Š” ๊ณผ์ •
์™„์„ฑ๋œ sumList

 

โœ๏ธ ํ’€์ด

์˜ค๋‹ต ํ’€์ด

function solution(triangle) {
    // ๋งจ ์ฒ˜์Œ ๊ฐ’ ๋”ํ•˜๊ณ , 
    // 0 -> 0, 1  1 -> 1, 2 ์ž๊ธฐ์ž์‹ , +1 ๋œ ์ธ๋ฑ์Šค๋กœ ๊ฐˆ ์ˆ˜ ์žˆ์Œ.
    // ๋‹ค์Œ ๋ฐฐ์—ด์—์„œ ์ œ์ผ ํฐ ๊ฐ’์„ ์ฐพ๊ณ  ๊ฐˆ ์ˆ˜ ์žˆ๋Š” ์ง€ ํ™•์ธ -> ๋ชป ๊ฐ€๋ฉด ๊ทธ ๋‹ค์Œ ํฐ ๊ฐ’ ์ฐพ๊ธฐ X
    // ๊ฐˆ ์ˆ˜ ์žˆ๋Š” ๊ฐ’๋“ค์„ ๋จผ์ € ๋ชจ์•„๋‘” ๋‹ค์Œ์— ์ œ์ผ ํฐ ๊ฐ’์œผ๋กœ ๊ฐ€๊ธฐ
    let answer = 0;
    let current = 0;
    answer += triangle[0][0];
    for(let i=1; i<triangle.length; i++){
        let access = [triangle[i][current], triangle[i][current + 1]];
        let max = Math.max(...access);
        let maxIndex = triangle[i].indexOf(max);
        answer += max;
        current = maxIndex;   
    }
    return answer;
}

 

์ •๋‹ต ํ’€์ด

function solution(triangle) {
    let answer = 0;
    let maxList = [[triangle[0][0]]];
    for(let i=1; i<triangle.length; i++){
        let sumList = [];
        for(let j=0; j<triangle[i].length; j++){
            if(j === 0) {
                sumList.push(triangle[i][j] + maxList[i-1][0]);
            }
            else if(j === triangle[i].length-1) {
                sumList.push(triangle[i][j] + maxList[i-1][j-1]);
            }
            else {
                if(maxList[i-1][j-1] > maxList[i-1][j]) {
                    sumList.push(triangle[i][j] + maxList[i-1][j-1]);
                }
                else {
                    sumList.push(triangle[i][j] + maxList[i-1][j]);
                }
            }
        }
        maxList.push(sumList);
    }
    return Math.max(...maxList[maxList.length-1]);
}