๊ด€๋ฆฌ ๋ฉ”๋‰ด

Daehyunii's Dev-blog

ํ•ฉ์ด ๊ฐ™์€ ๋ถ€๋ถ„์ง‘ํ•ฉ(์ด์ง„ํŠธ๋ฆฌ DFS) ๋ณธ๋ฌธ

๐Ÿ“š Language & CS knowledge/Algorithm (๊ธฐ์ดˆ๋ฌธ์ œํ’€์ด)

ํ•ฉ์ด ๊ฐ™์€ ๋ถ€๋ถ„์ง‘ํ•ฉ(์ด์ง„ํŠธ๋ฆฌ DFS)

Daehyunii 2022. 9. 7. 21:52

๋ฌธ์ œ(์ถœ์ฒ˜ : ์ธํ”„๋Ÿฐ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ๋ฌธ์ œํ’€์ด ๊ฐ•์˜, ์ •๋ณด์˜ฌ๋ฆผํ”ผ์•„๋“œ)

N๊ฐœ์˜ ์›์†Œ๋กœ ๊ตฌ์„ฑ๋œ ์ž์—ฐ์ˆ˜ ์ง‘ํ•ฉ์ด ์ฃผ์–ด์ง€๋ฉด, ์ด ์ง‘ํ•ฉ์„ ๋‘ ๊ฐœ์˜ ๋ถ€๋ถ„์ง‘ํ•ฉ์œผ๋กœ ๋‚˜๋ˆ„์—ˆ์„ ๋•Œ ๋‘ ๋ถ€๋ถ„์ง‘ํ•ฉ์˜ ์›์†Œ์˜ ํ•ฉ์ด ์„œ๋กœ ๊ฐ™์€ ๊ฒฝ์šฐ๊ฐ€ ์กด์žฌํ•˜๋ฉด “YES"๋ฅผ ์ถœ๋ ฅํ•˜๊ณ , ๊ทธ๋ ‡์ง€ ์•Š์œผ๋ฉด ”NO"๋ฅผ ์ถœ๋ ฅํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์„ธ์š”.
๋‘˜๋กœ ๋‚˜๋‰˜๋Š” ๋‘ ๋ถ€๋ถ„์ง‘ํ•ฉ์€ ์„œ๋กœ์†Œ ์ง‘ํ•ฉ์ด๋ฉฐ, ๋‘ ๋ถ€๋ถ„์ง‘ํ•ฉ์„ ํ•ฉํ•˜๋ฉด ์ž…๋ ฅ์œผ๋กœ ์ฃผ์–ด์ง„ ์›๋ž˜์˜ ์ง‘ํ•ฉ์ด ๋˜์–ด ํ•ฉ๋‹ˆ๋‹ค.

์˜ˆ๋ฅผ ๋“ค์–ด {1, 3, 5, 6, 7, 10}์ด ์ž…๋ ฅ๋˜๋ฉด {1, 3, 5, 7} = {6, 10} ์œผ๋กœ ๋‘ ๋ถ€๋ถ„์ง‘ํ•ฉ์˜ ํ•ฉ์ด 16์œผ๋กœ ๊ฐ™์€ ๊ฒฝ์šฐ๊ฐ€ ์กด์žฌํ•˜๋Š” ๊ฒƒ์„ ์•Œ ์ˆ˜ ์žˆ๋‹ค.

 

โ–ฃ ์ž…๋ ฅ์„ค๋ช…
์ฒซ ๋ฒˆ์งธ ์ค„์— ์ž์—ฐ์ˆ˜ N(1<=N<=10)์ด ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค.
๋‘ ๋ฒˆ์งธ ์ค„์— ์ง‘ํ•ฉ์˜ ์›์†Œ N๊ฐœ๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๊ฐ ์›์†Œ๋Š” ์ค‘๋ณต๋˜์ง€ ์•Š์œผ๋ฉฐ, ๊ทธ ํฌ๊ธฐ๋Š” 1,000,000 ์ดํ•˜์ž…๋‹ˆ๋‹ค.

 

โ–ฃ ์ถœ๋ ฅ์„ค๋ช…
์ฒซ ๋ฒˆ์งธ ์ค„์— “YES" ๋˜๋Š” ”NO"๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.

 

โ–ฃ ์ž…๋ ฅ์˜ˆ์ œ 1

6
1 3 5 6 7 10

 

โ–ฃ ์ถœ๋ ฅ์˜ˆ์ œ 1

YES

Tip

 

๋ฌธ์ œํ’€์ด

//์ •๋‹ต
function solution(arr){
    let answer="NO", flag=0;
    let total=arr.reduce((a, b)=>a+b, 0);
    let n=arr.length;
    function DFS(L, sum){
        if(flag) return; // ํ•œ ๋ฒˆ ์ฐพ๊ฒŒ ๋˜๋ฉด ๊ทธ ๋’ค์— ๋” ์ฐพ์„ ํ•„์š”๊ฐ€ ์—†์œผ๋ฏ€๋กœ, ๊ณ„์† ์ฐพ๋Š”๊ฑฐ ๋ฐฉ์ง€์šฉ
        if(L===n){
            if((total-sum)===sum){
                answer="YES"; 
                flag=1; // ํ•œ ๋ฒˆ ์ฐพ๊ฒŒ ๋˜๋ฉด ๊ทธ ๋’ค์—๋Š” ๋” ์ฐพ์„ ํ•„์š”๊ฐ€ ์—†์œผ๋ฏ€๋กœ, ๊ณ„์† ์ฐพ๋Š”๊ฑฐ ๋ฐฉ์ง€์šฉ
            }
        }
        else{
            DFS(L+1, sum+arr[L]);
            DFS(L+1, sum);
        }
    }
    DFS(0, 0);
    return answer;
}

let arr=[1, 3, 5, 6, 7, 10];
console.log(solution(arr));