알고리즘 기초 다지기 프로젝트 (feat. 코드없는 프로그래밍) [2021년 07월 12일]
Leetcode - Coin Change 2
문제: LeetCode - 518. Coin Change 2
문제 요약
- coins에 들어있는 종류의 갯수가 무제한 있을때, amount를 만들수있는 조합의 갯수를 구하라.
- Knapsack 문제의 변형
코드
const change = (amount, coins) => {
const arrDP = Array.from({ length: coins.length + 1 }, () =>
Array.from({ length: amount + 1 }, (_, i) => (i === 0 ? 1 : 0)),
);
for (let rowIdx = 1; rowIdx < arrDP.length; rowIdx++) {
const prevRowIdx = rowIdx - 1;
const prevRow = arrDP[prevRowIdx];
const currCoin = coins[rowIdx - 1];
for (let colIdx = 1; colIdx < amount + 1; colIdx++) {
const tmpColValue = arrDP[rowIdx][colIdx - currCoin];
const prevRowColValue = prevRow[colIdx];
arrDP[rowIdx][colIdx] =
(typeof tmpColValue === 'undefined' || tmpColValue < 0
? 0
: tmpColValue) + prevRowColValue;
}
}
return arrDP[arrDP.length - 1][amount];
};
change(5, [1, 2, 5]);
참고 이미지
끄적끄적
- 조금은 알겠는데 모르겠다. 강의에 나온대로 만든..
- 그래도 예전엔 강의에 나온대로 해도 못풀었는데 그나마 나은듯..?
알고리즘 기초 다지기 프로젝트 (feat. 코드없는 프로그래밍) [2021년 07월 12일]
Leetcode - Coin Change 2
문제: LeetCode - 518. Coin Change 2
문제 요약
코드
참고 이미지
끄적끄적