Skip to content

Commit 3b6be23

Browse files
committed
Feat: solve #269
1 parent 7aa8d5f commit 3b6be23

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

โ€Žcoin-change/crumbs22.cpp

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
#include <vector>
2+
#include <algorithm>
3+
using namespace std;
4+
5+
/*
6+
- dp[i]: ๊ธˆ์•ก i๋ฅผ ๋งŒ๋“œ๋Š” ์ตœ์†Œ ์ฝ”์ธ์ˆ˜
7+
- ์ดˆ๊ธฐ๊ฐ’
8+
- dp[0] = 0
9+
- ๊ทธ ์™ธ์—๋Š” amount + 1 (๋„๋‹ฌํ•  ์ˆ˜ ์—†๋Š” ๊ฐ’)์œผ๋กœ ์ดˆ๊ธฐํ™”
10+
- ํ˜„์žฌ ๊ธˆ์•ก i๋ฅผ ๋งŒ๋“ค๊ธฐ ์œ„ํ•ด์„œ
11+
์ด์ „ ๊ธˆ์•ก์ธ i - c๋ฅผ ๋งŒ๋“ค๊ณ , ๊ฑฐ๊ธฐ์— ์ฝ”์ธ c๋ฅผ ๋” ์ผ์„ ๋•Œ ์ตœ์†Œ๊ฐ’์„ ๊ฐฑ์‹ ํ•จ
12+
์˜ˆ์‹œ) coins = [1, 2, 5], i = 3์ผ ๋•Œ
13+
c = 1 -> 3 >= 1 ์ด๋ฏ€๋กœ dp[3] = min(dp[3], dp[2] + 1) ๊ฐฑ์‹ 
14+
c = 2 -> 3 >= 2 ์ด๋ฏ€๋กœ dp[3] = min(dp[3], dp[1] + 1) ๊ฐฑ์‹ 
15+
c = 5 -> 3 < 5 ์ด๋ฏ€๋กœ ๊ฑด๋„ˆ๋œ€
16+
=> i - c๊ฐ€ ์Œ์ˆ˜๋ฉด ๋ฐฐ์—ด ๋ฒ”์œ„๋ฅผ ๋ฒ—์–ด๋‚˜๋ฏ€๋กœ i >= c์ผ๋•Œ๋งŒ ์—ฐ์‚ฐ์‚ฐ
17+
*/
18+
class Solution {
19+
public:
20+
int coinChange(vector<int>& coins, int amount) {
21+
// dp ํ…Œ์ด๋ธ” ์ดˆ๊ธฐํ™”
22+
vector<int> dp(amount + 1, amount + 1);
23+
dp[0] = 0;
24+
25+
// bottom up ์—ฐ์‚ฐ
26+
for (int i = 1; i <= amount; ++i) {
27+
for (int c : coins) {
28+
if (i >= c) {
29+
dp[i] = min(dp[i], dp[i - c] + 1);
30+
}
31+
}
32+
}
33+
34+
return (dp[amount] > amount) ? -1 : dp[amount];
35+
}
36+
};

0 commit comments

Comments
ย (0)