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

[์ธํ”„๋Ÿฐ ์„น์…˜8] ๋™์ „๊ตํ™˜ (Javascript)

์€์ง„ 2021. 6. 29. 17:38

์ธํ”„๋Ÿฐ

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

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


โœ๏ธIdea Sketch

2021-06-29

1. ๊ฐ€์žฅ ์ ์€ ์ˆ˜์˜ ๋™์ „์œผ๋กœ ๊ตํ™˜

  • DP์ธ์ง€ ๊ทธ๋ฆฌ๋””์ธ์ง€ ํ—ท๊ฐˆ๋ฆผ

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

  • ์ค‘๋ณต์ˆœ์—ด๋กœ ๊ตฌํ˜„ (for ๋ฐ˜๋ณต๋ฌธ)
  • ๊ฑฐ์Šค๋ฆ„๋ˆ์ด target๋ณด๋‹ค ํฌ๊ฑฐ๋‚˜ ๊ฐ™์œผ๋ฉด ์ข…๋ฃŒ --> Math.min()์„ ์จ์•ผํ•˜๋‚˜?
  • ๊ฑฐ์Šค๋ฆ„๋ˆ์ด target๊ณผ ๊ฐ™์€ ๊ฒฝ์šฐ, ๋™์ „์„ ๋ฝ‘์€ ํšŸ์ˆ˜์ธ v๋ฅผ ์ถœ๋ ฅ
if (sum >= target) {
  if (sum === target) console.log(v);
  return;
}

3. DFS ๋กœ์ง

  • ์ค‘๋ณต๊ฐ€๋Šฅ์ด๋ฏ€๋กœ, v๋Š” ๋ฝ‘์€ ์ˆซ์ž๊ฐ€ ์•„๋‹ˆ๋ผ ๋ฝ‘์€ ํšŸ์ˆ˜
  • for ๋ฐ˜๋ณต๋ฌธ ์‚ฌ์šฉ
for (let i=0; i<arr.length; i++) {
  sum += arr[i];
  DFS(v+1);
  sum -= arr[i];
}

4. v์˜ ์ดˆ๊ธฐ๊ฐ’

  • ๋™์ „์„ ์ถ”๊ฐ€ํ•˜๊ณ  ๋‚˜์„œ v+1
  • ์ดˆ๊ธฐ๊ฐ’์€ 0


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

2021-06-29

let arr = [1, 2, 5];
let target = 15;
let sum = 0;
let min = Number.MAX_SAFE_INTEGER;

function DFS(v) {
  if (sum >= target) {
    if (sum === target) min = Math.min(min, v);
    return;
  }

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

DFS(0);
console.log(min);