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

Daehyunii's Dev-blog

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

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

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

Daehyunii 2022. 9. 7. 21:49

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

 

์ž์—ฐ์ˆ˜ N์ด ์ฃผ์–ด์ง€๋ฉด 1๋ถ€ํ„ฐ N๊นŒ์ง€์˜ ์›์†Œ๋ฅผ ๊ฐ–๋Š” ์ง‘ํ•ฉ์˜ ๋ถ€๋ถ„์ง‘ํ•ฉ์„ ๋ชจ๋‘ ์ถœ๋ ฅํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ ์„ ์ž‘์„ฑํ•˜์„ธ์š”.

 

โ–ฃ ์ž…๋ ฅ์„ค๋ช…
์ฒซ ๋ฒˆ์งธ ์ค„์— ์ž์—ฐ์ˆ˜ N(1<=N<=10)์ด ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค.

 

โ–ฃ ์ถœ๋ ฅ์„ค๋ช…
์ฒซ ๋ฒˆ์งธ ์ค„๋ถ€ํ„ฐ ๊ฐ ์ค„์— ํ•˜๋‚˜์”ฉ ๋ถ€๋ถ„์ง‘ํ•ฉ์„ ์•„๋ž˜์™€ ์ถœ๋ ฅ์˜ˆ์ œ์™€ ๊ฐ™์€ ์ˆœ์„œ๋กœ ์ถœ๋ ฅํ•œ๋‹ค. ๋‹จ ๊ณต์ง‘ํ•ฉ์€ ์ถœ๋ ฅํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.

 

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

 

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

123
12
13

1 23 2
3

Tip

 

๋ฌธ์ œํ’€์ด

//์ •๋‹ต
function solution(n){
    let answer=[];
    let ch=Array.from({length:n+1}, ()=>0);
    function DFS(L){
        if(L===n+1){
            let tmp="";
            for(let i=1; i<=n; i++){
                if(ch[i]===1) tmp+=(i+" ");
            }
            if(tmp.length>0) answer.push(tmp.trim()); //๊ณต์ง‘ํ•ฉ ์ œ์™ธ
        }
        else{
            ch[L]=1;
            DFS(L+1);
            ch[L]=0;
            DFS(L+1);
        }
    }
    DFS(1);
    return answer;
}

console.log(solution(3));