Skip to content

Commit

Permalink
add: solve #269 Coin Change with ts
Browse files Browse the repository at this point in the history
  • Loading branch information
Yjason-K committed Jan 2, 2025
1 parent bf38b87 commit 127f9a6
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions coin-change/Yjason-K.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/**
* 가지고 μžˆλŠ” 동전을 μ΅œλŒ€ν•œ ν™œμš©ν•˜μ—¬ μ΅œμ†Œμ˜ μ‘°ν•©μœΌλ‘œ amountλ₯Ό λ§Œλ“œλŠ” μ΅œμ†Œ 동전 개수 κ΅¬ν•˜λŠ” ν•¨μˆ˜
*
* @param {number[]} coins - μ‚¬μš© κ°€λŠ₯ν•œ 동전 λ°°μ—΄
* @param {number} amount - λ§Œλ“€μ–΄μ•Ό ν•˜λŠ” 총합
* @returns {number}
*
* μ‹œκ°„ λ³΅μž‘λ„ O(n * m)
* - n은 동전 λ°°μ—΄μ˜ 크기
* - m은 amount
*
* 곡간 λ³΅μž‘λ„ (n);
* - 큐에 μ΅œλŒ€ n개의 μš”μ†Œκ°€ λ“€μ–΄κ°ˆ 수 있음
*/
function coinChange(coins: number[], amount: number): number {
// 총합이 0인 경우 0 λ°˜ν™˜
if (amount === 0) return 0;

// λ„ˆλΉ„ μš°μ„  탐색을 ν™œμš©ν•œ 풀이

const queue: [number, number] [] = [[0, 0]]; // [ν˜„μž¬ 총합, 깊이]
const visited = new Set<number>();

while (queue.length > 0) {
const [currentSum, depth] = queue.shift()!;

// 동전을 ν•˜λ‚˜μ”© λ”ν•΄μ„œ λ‹€μŒ κΉŠμ΄μ„ 탐색
for (const coin of coins) {
const nextSum = currentSum + coin;

// λͺ©ν‘œ κΈˆμ•‘μ— λ„λ‹¬ν•˜λ©΄ ν˜„μž¬ 깊이λ₯Ό λ°˜ν™˜
if (nextSum === amount) return depth + 1;

// 아직 총합에 λ„λ‹¬ν•˜μ§€ μ•Šμ•˜κ³ , μ€‘λ³΅λ˜μ§€ μ•Šμ•„ 탐색 κ°€λŠ₯ν•œ 경우
if (nextSum < amount && !visited.has(nextSum)) {
queue.push([nextSum, depth + 1]);
visited.add(nextSum)
}

}
}

// 탐색 쑰건을 μ™„λ£Œ 해도 경우의 수λ₯Ό 찾지 λͺ»ν•œ 경우
return -1;
}

0 comments on commit 127f9a6

Please sign in to comment.