본문 바로가기
BEB/algorithm

46_0-1Knapsack

by ddanss 2023. 1. 15.
728x90

이론은

https://cocoon1787.tistory.com/206 이거 보시면 편하실거에요!

이론이 너무 어렵습니다 ㅠㅠㅠ

 

const knapsack = function (weight, items) {
  let d =  Array.from(Array(items.length+1), () => Array(weight+1).fill(0))
  items.unshift([0,0]); //[[0,0], [10,60], [20,100], [30,120]] 이런식으로 오게하기 위해 넣은것
  
  for(let i=1; i<items.length; i++) {
    for(let j=1; j<=weight; j++) {
      if(j-items[i][0] >= 0) d[i][j] = Math.max(d[i-1][j], d[i-1][j-items[i][0]]+items[i][1]);
      else d[i][j] = d[i-1][j];
    }
  }
  return d[items.length-1][weight];
}

 

반응형

'BEB > algorithm' 카테고리의 다른 글

47_Dijkstra  (0) 2023.01.22
48_FloydWarshall  (0) 2023.01.19
45_subsetSum  (0) 2023.01.09
41_countIslands  (0) 2022.12.22
40_longestPalindrome 가장긴 팰린드롬  (0) 2022.12.20

댓글