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

[์ธํ”„๋Ÿฐ ์„น์…˜8] ์ˆ˜๋“ค์˜ ์กฐํ•ฉ (Javascript)

์€์ง„ 2021. 6. 30. 11:44

์ธํ”„๋Ÿฐ

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

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


โœ๏ธIdea Sketch

2021-06-30

1. K๊ฐœ๋ฅผ ๋ฝ‘๋Š” ์กฐํ•ฉ์˜ ํ•ฉ์ด ์ž„์˜์˜ ์ •์ˆ˜ M์˜ ๋ฐฐ์ˆ˜์ธ ๊ฐœ์ˆ˜

2. DFS ์ข…๋ฃŒ์กฐ๊ฑด

  • ๋ฝ‘๋Š” ํšŸ์ˆ˜ v >= k ์ธ ๊ฒฝ์šฐ, return;
  • sum % m === 0์ธ ๊ฒฝ์šฐ, cnt++;
if (v >= k) {
  if (sum % m === 0) cnt++;
  return;
}

3. DFS ๋กœ์ง

  • ์กฐํ•ฉ์„ ๊ตฌํ•˜๋ฏ€๋กœ ์ค‘๋ณตX
  • DFS ๋งค๊ฐœ๋ณ€์ˆ˜ : ๋ฝ‘์€ ํšŸ์ˆ˜ v, ์ด์ „์— ๋ฝ‘์€ arr ์›์†Œ์˜ ์ธ๋ฑ์Šค u
for (let i=u+1; i<arr.length, i++) {
  sum += arr[i];
  DFS(v+1, i);
  sum -= arr[i];
}

4. DFS ์ดˆ๊ธฐ๊ฐ’

  • DFS(0, -1);
  • v : ๊ตฌ์Šฌ ๋ฝ‘์€ ํšŸ์ˆ˜๊ฐ€ 0ํšŒ
  • u : arr์—์„œ ๋ฝ‘์€ ๊ตฌ์Šฌ์˜ ์ธ๋ฑ์Šค, ์•„์ง ๋ฝ‘๊ธฐ ์ „์ด๋ฏ€๋กœ -1


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

2021-06-30

let k = 3;
let m = 6;
let arr = [2, 4, 5, 8, 12];

let cnt = 0;
let sum = 0;

function DFS(v, u) {
  if (v >= k) {
    if (sum % m === 0) cnt++;
    return;
  }

  for (let i = u + 1; i < arr.length; i++) {
    sum += arr[i];
    DFS(v + 1, i);
    sum -= arr[i];
  }
}

DFS(0, -1);
console.log(cnt);