ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

๋ฌธ์ œ

๋‹ค์Œ๊ณผ ๊ฐ™์ด ์—ฌ๋Ÿฌ ๋‹จ์œ„์˜ ๋™์ „๋“ค์ด ์ฃผ์–ด์ ธ ์žˆ์„๋•Œ ๊ฑฐ์Šค๋ฆ„๋ˆ์„ ๊ฐ€์žฅ ์ ์€ ์ˆ˜์˜ ๋™์ „์œผ๋กœ ๊ตํ™˜ํ•ด์ฃผ๋ ค๋ฉด ์–ด๋–ป๊ฒŒ ์ฃผ๋ฉด ๋˜๋Š”๊ฐ€?๊ฐ ๋‹จ์œ„์˜ ๋™์ „์€ ๋ฌดํ•œ์ • ์“ธ ์ˆ˜ ์žˆ๋‹ค.

 

๋ฌธ์ œํ’€์ด

ํŠธ๋ฆฌ DFS

 

์ฝ”๋“œ

function solution(arr, m) {
  let answer = Number.MAX_SAFE_INTEGER;
  let n = arr.length;

  function DFS(L, sum) {
    if(sum > m) return; //๊ฑฐ์Šค๋ฆ„๋ˆ ๊ธˆ์•ก์„ ํ•ฉ์‚ฐ ๊ธˆ์•ก์ด ๋„˜์–ด์„ฐ์„ ๊ฒฝ์šฐ
    if(sum === m) {
      answer = Math.min(answer, L);
    }
    else {
      for(let i = 0; i < n; i++) {
        DFS(L + 1, sum + arr[i]);
      }
    }
  }
  
  
  DFS(0, 0);
  return answer;
}

const arr = [1, 2, 5];
console.log(solution(arr, 15));

 

DFS-Cut Edge

์œ„ ์ฝ”๋“œ๋งŒ์œผ๋กœ๋„ ๋™์ „์˜ ๊ฐ€์žฅ ์ ์€ ์ˆ˜๋ฅผ ๊ตฌํ•  ์ˆ˜ ์žˆ์ง€๋งŒ ๋‹ค์Œ๊ณผ ๊ฐ™์€ ๋ฌธ์ œ๊ฐ€ ์žˆ๋‹ค.๊ฑฐ์Šค๋ฆ„๋ˆ์ด ๋˜๋Š” ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ์ฝ˜์†” ์ฐฝ์—์„œ ํ™•์ธํ•œ ๊ฒฐ๊ณผ,

๊ฒฐ๊ณผ ์ถœ๋ ฅ
๋™์ „ ์ข…๋ฅ˜์˜ ๊ฐฏ์ˆ˜๊ฐ€ 5๊ฐœ์ผ ๊ฒฝ์šฐ ์ด๋ณด๋‹ค ๋” ๋งŽ์€ ๋™์ „ ์ข…๋ฅ˜๋ฅผ ์‚ฌ์šฉํ•ด์„œ ๊ฑฐ์Šค๋ฆ„๋ˆ๊ณผ ๊ฐ™์€ ๊ธˆ์•ก์„ ์‚ฐ์ถœํ•˜๋Š” ์ž‘์—…์€ ํ˜„์žฌ ๊ฐ€์žฅ ์ ์€ ์ˆ˜์˜ ๋™์ „์œผ๋กœ ๊ตํ™˜ํ•ด์•ผ ํ•˜๋Š” ์ด ๋ฌธ์ œ์—์„œ ๋ถˆํ•„์š”ํ•˜๋‹ค.์ด๋Ÿฌํ•œ ๋ถˆํ•„์š”ํ•œ ์ž‘์—…์„ ์ƒ๋žตํ•˜๊ธฐ ์œ„ํ•ด์„œ๋Š” ํ˜„์žฌ๊นŒ์ง€ ๋™์ „ ์ข…๋ฅ˜์˜ ๊ฐฏ์ˆ˜๋ฅผ ์ €์žฅํ•˜๊ณ  ์žˆ๋Š” ๋ณ€์ˆ˜๋ณด๋‹ค ํ˜„์žฌ ๋ ˆ๋ฒจ ๊ฐ’(์ƒˆ๋กญ๊ฒŒ ๊ตฌํ•˜๋Š” ๊ฒฝ์šฐ์˜ ์ˆ˜)์ด ํฌ๊ฑฐ๋‚˜ ์ž‘์„ ๊ฒฝ์šฐ ์žฌ๊ท€๋ฅผ ์ข…๋ฃŒํ•˜๋ฉด ๋œ๋‹ค.

function solution(arr, m) {
  let answer = Number.MAX_SAFE_INTEGER;
  let n = arr.length;

  function DFS(L, sum) {
    if(answer <= L) return; //Cut Edge
    if(sum > m) return; 
    if(sum === m) {
      answer = Math.min(answer, L);
    }
    else {
      for(let i = 0; i < n; i++) {
        DFS(L + 1, sum + arr[i]);
      }
    }
  }
  
  
  DFS(0, 0);
  return answer;
}

const arr = [1, 2, 5];
console.log(solution(arr, 15));
๋Œ“๊ธ€
๊ณต์ง€์‚ฌํ•ญ
์ตœ๊ทผ์— ์˜ฌ๋ผ์˜จ ๊ธ€
์ตœ๊ทผ์— ๋‹ฌ๋ฆฐ ๋Œ“๊ธ€
Total
Today
Yesterday
๋งํฌ
TAG
more
ยซ   2025/01   ยป
์ผ ์›” ํ™” ์ˆ˜ ๋ชฉ ๊ธˆ ํ† 
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
๊ธ€ ๋ณด๊ด€ํ•จ