-
Notifications
You must be signed in to change notification settings - Fork 126
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
45 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |