์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ์•Œ๊ณ ๋ฆฌ์ฆ˜

[์ธํ”„๋Ÿฐ ์„น์…˜8] ํ•ฉ์ด ๊ฐ™์€ ๋ถ€๋ถ„์ง‘ํ•ฉ (Javascript)

์€์ง„ 2021. 6. 29. 15:18

์ธํ”„๋Ÿฐ

๐Ÿ‘ฉ๐Ÿปโ€๐Ÿ’ป๋ฌธ์ œ๋งํฌ

[์ธํ”„๋Ÿฐ ์„น์…˜8] ํ•ฉ์ด ๊ฐ™์€ ๋ถ€๋ถ„์ง‘ํ•ฉ (Javascript)
์œ ๋ฃŒ ๊ฐ•์˜์ธ ๊ด€๊ณ„๋กœ ๋ฌธ์ œ ์„ค๋ช…์€ ์ƒ๋žตํ•ฉ๋‹ˆ๋‹ค.


โœ๏ธIdea Sketch

2021-06-29

1. (์ง‘ํ•ฉ์˜ ํ•ฉ === ์ „์ฒด ์ง‘ํ•ฉ์˜ ํ•ฉ - ์ง‘ํ•ฉ์˜ ํ•ฉ) ์ธ์ง€ ํ™•์ธํ•˜์—ฌ true๋ฉด "YES", false๋ฉด "NO"

  • ํ•œ ๋ฒˆ์ด๋ผ๋„ ์กฐ๊ฑด์„ ๋งŒ์กฑํ•˜๋ฉด ์ „์ฒด์ข…๋ฃŒ
if (n >= arr.length) {
  let sum = res.reduce((a, b) => a + b, 0);
  if (su)
}

2. ๋ถ€๋ถ„์ง‘ํ•ฉ์˜ ํ•ฉ ๊ตฌํ•˜๋Š” 2๊ฐ€์ง€ ๋ฐฉ๋ฒ•

  • ๋ฐฉ๋ฒ• 1. res.push(), res.pop()
let res = [];
let total = arr.reduce((a, b) => a + b, 0);

function DFS(n) {
  if (n >= arr.length) {
    let sum = res.reduce((a, b) => a + b, 0);
    if (sum === total - sum) return "YES"
  }
  res.push(arr[n]);
  DFS(n+1);
}
  • ๋ฐฉ๋ฒ• 2. sum += n, sum -= n
let sum = 0;
let total = arr.reduce((a, b) => a + b, 0);

function DFS(n) {
  if (n >= arr.length) {
    if (sum === total - sum) return "YES";
  }
  sum += arr[n];
  DFS(n+1);
  sum -= arr[n];
  DFS(n+1);
}

3. ํ•œ ๋ฒˆ์ด๋ผ๋„ ์กฐ๊ฑด์„ ๋งŒ์กฑํ•˜๋ฉด ์ „์ฒด์ข…๋ฃŒํ•˜๋Š” ๋ฐฉ๋ฒ•

  • return flag ์ƒ์„ฑ
  • DFS ๋‚ด๋ถ€์—์„œ flag = true/false
  • DFS ์™ธ๋ถ€์—์„œ flag ๊ฐ’์— ๋”ฐ๋ผ YES/NO ์ถœ๋ ฅ
let flag = false;

function DFS (n) {
  if (flag) return;
  else {}
}

DFS(0);
console.log(flag ? "YES" : "NO");


โœ๏ธ์†Œ์Šค์ฝ”๋“œ

2021-06-29

let arr = [1, 3, 5, 6, 7, 10];
let total = arr.reduce((a, b) => a + b, 0);
let sum = 0;
let flag = false;

function DFS(n) {
  if (flag) return;
  if (n >= arr.length) {
    if (sum === total - sum) flag = true;
    return;
  }
  sum += arr[n];
  DFS(n + 1);
  sum -= arr[n];
  DFS(n + 1);
}

DFS(0);
console.log(flag ? "YES" : "NO");