๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
์นดํ…Œ๊ณ ๋ฆฌ ์—†์Œ

[ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ(JavaScript) ] section08 - 5 - ํ•ฉ์ด ๊ฐ™์€ ๋ถ€๋ถ„์ง‘ํ•ฉ(DFS: ์•„๋งˆ์กด ์ธํ„ฐ๋ทฐ)

by YWTechIT 2021. 9. 17.
728x90

๐Ÿ“ section08 - 5 - ํ•ฉ์ด ๊ฐ™์€ ๋ถ€๋ถ„์ง‘ํ•ฉ(DFS: ์•„๋งˆ์กด ์ธํ„ฐ๋ทฐ)

N๊ฐœ์˜ ์›์†Œ๋กœ ๊ตฌ์„ฑ๋œ ์ž์—ฐ์ˆ˜ ์ง‘ํ•ฉ์ด ์ฃผ์–ด์ง€๋ฉด, ์ด ์ง‘ํ•ฉ์„ ๋‘ ๊ฐœ์˜ ๋ถ€๋ถ„์ง‘ํ•ฉ์œผ๋กœ ๋‚˜๋ˆŒ ๋•Œ ๋‘ ๋ถ€๋ถ„์ง‘ํ•ฉ์˜ ์›์†Œ์˜ ํ•ฉ์ด ์„œ๋กœ ๊ฐ™์€ ๊ฒฝ์šฐ๋ฉด YES, ๊ทธ๋ ‡์ง€ ์•Š์œผ๋ฉด NO๋ฅผ ์ถœ๋ ฅํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜๋Š” ๋ฌธ์ œ๋‹ค. ๋งˆ์ฐฌ๊ฐ€์ง€๋กœ ์ˆœ์„œ๋„๋ฅผ ๊ทธ๋ ค์„œ ์ดํ•ดํ•˜๋Š” ๊ฒƒ์ด ๊ฐ€์žฅ ๋น ๋ฅด๋‚˜, ์ž…๋ ฅ ์˜ˆ์ œ๊ฐ€ n=6์ด๋ฏ€๋กœ(์ด 64๊ฐœ์˜ ๊ฐ€์ง€๋ฅผ ๊ทธ๋ ค์•ผํ•จ) ๋”ฐ๋กœ ์ˆœ์„œ๋„๋ฅผ ๊ทธ๋ฆฌ์ง€ ์•Š๊ณ  ๊ทธ๋ฆผ์ฒ˜๋Ÿผ ๊ทธ๋ฆฌ๋ฉด ๋œ๋‹ค.

 

  1. ์–ด๋–ค ๋ถ€๋ถ„์ง‘ํ•ฉ์˜ ํ•ฉ์ด ๊ฐ™์€์ง€๋ฅผ ์ฐพ์œผ๋ ค๋ฉด ๋ถ€๋ถ„์ง‘ํ•ฉ์ด ๋‚˜์˜ฌ ์ˆ˜ ์žˆ๋Š” ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ๋ชจ๋‘ ๊ตฌํ•œ๋‹ค. n=6์ด๋ฏ€๋กœ ์ด ๋ถ€๋ถ„์ง‘ํ•ฉ์˜ ๊ฐœ์ˆ˜๋Š” 2^6=64๊ฐ€ ๋‚˜์˜จ๋‹ค.
  2. ํ•ฉ์ด ๊ฐ™์€ ๋ถ€๋ถ„์ง‘ํ•ฉ์„ ์ฐพ์„ ๋•Œ, A, B ๋ถ€๋ถ„์ง‘ํ•ฉ์„ ๋ชจ๋‘ ๊ตฌํ•˜์ง€ ์•Š๊ณ  ํ•œ ๋ถ€๋ถ„์ง‘ํ•ฉ๋งŒ ๊ตฌํ•˜๊ณ  ๋‚˜์„œ sum(๋ฐฐ์—ด) - aSum(ํ•œ ๋ถ€๋ถ„์ง‘ํ•ฉ) = aSum์ด๋ฉด aSum = bSum์ด ๋œ๋‹ค.
  3. 11๋ฒˆ์งธ ์ฝ”๋“œ์— edgeCut ๋ฐฉ์‹์„ ์ ์šฉํ–ˆ๋Š”๋ฐ, edgeCut์ด๋ž€ ๋ฌธ์ œ์—์„œ ์ฃผ์–ด์ง„ ์ถœ๋ ฅ์„ ๋งŒ์กฑํ•˜์—ฌ ๋” ์ด์ƒ ๊ณ„์‚ฐ ํ•  ํ•„์š” ์—†์„ ๋•Œ ๋‚จ์€ ์žฌ๊ท€๋ฅผ ๊ฑฐ์น˜์ง€ ์•Š๊ณ  returnํ•˜์—ฌ ์ถœ๋ ฅํ•˜๋Š” ๋ฐฉ์‹์ด๋‹ค. ๋ถˆ ํ•„์š”ํ•œ ๊ณ„์‚ฐ์„ ์ค„์—ฌ ์‹œ๊ฐ„์„ ์กฐ๊ธˆ์ด๋‚˜๋งˆ ๋” ๋‹จ์ถ•ํ•  ์ˆ˜ ์žˆ๋Š” ์žฅ์ ์ด ์žˆ๋‹ค.

 

728x90

 

let n = 6;
let arr = [1, 3, 5, 6, 7, 10];

console.log(solution(n, arr));

function solution(n, arr){
  let total = arr.reduce((prev, cur) => prev+cur);
  let flag = false;

  function DFS(L, sum){
    if (flag) return;  // edge cut
    if (L === n){
      if (total-sum===sum) flag = true
    }else{
      DFS(L+1, sum+arr[L]);
      DFS(L+1, sum);
    }
  }

  DFS(0, 0);
  return flag ? "YES" : "NO";
}
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€