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

[์ธํ”„๋Ÿฐ ์„น์…˜8] ๋ฐ”๋‘‘์ด ์Šน์ฐจ (Javascript)

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

์ธํ”„๋Ÿฐ

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

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


โœ๏ธIdea Sketch

2021-06-29

1. C๋ฅผ ๋„˜์ง€ ์•Š์œผ๋ฉด์„œ ๊ฐ€์žฅ ๋ฌด๊ฒ๊ฒŒ ์‹ฃ๊ธฐ

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

if (n >= arr.length) {
  if (sum <= c) max = Math.max(max, sum);
  return ;
}

3. DFS ํ˜ธ์ถœ๋กœ์ง

sum += arr[n];
DFS(n+1);
sum -= arr[n];
DFS(n+1);


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

2021-06-29

let arr = [81, 58, 42, 33, 61];
let c = 259;
let sum = 0;
let max = Number.MIN_SAFE_INTEGER;

function DFS(n) {
  if (n >= arr.length) {
    if (sum <= c) max = Math.max(max, sum);
    return;
  }
  sum += arr[n];
  DFS(n + 1);
  sum -= arr[n];
  DFS(n + 1);
}

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