Skip to content

Commit e4d9550

Browse files
authored
feat: add swift implementation to lcof2 problem: No.103 (doocs#3616)
1 parent a08c8cd commit e4d9550

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

lcof2/剑指 Offer II 103. 最少的硬币数目/README.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,26 @@ var coinChange = function (coins, amount) {
169169
};
170170
```
171171

172+
#### Swift
173+
174+
```swift
175+
class Solution {
176+
func coinChange(_ coins: [Int], _ amount: Int) -> Int {
177+
var dp = [Int](repeating: amount + 1, count: amount + 1)
178+
dp[0] = 0
179+
180+
for coin in coins {
181+
if coin > amount { continue }
182+
for j in coin...amount {
183+
dp[j] = min(dp[j], dp[j - coin] + 1)
184+
}
185+
}
186+
187+
return dp[amount] > amount ? -1 : dp[amount]
188+
}
189+
}
190+
```
191+
172192
<!-- tabs:end -->
173193

174194
<!-- solution:end -->
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
class Solution {
2+
func coinChange(_ coins: [Int], _ amount: Int) -> Int {
3+
var dp = [Int](repeating: amount + 1, count: amount + 1)
4+
dp[0] = 0
5+
6+
for coin in coins {
7+
if coin > amount { continue }
8+
for j in coin...amount {
9+
dp[j] = min(dp[j], dp[j - coin] + 1)
10+
}
11+
}
12+
13+
return dp[amount] > amount ? -1 : dp[amount]
14+
}
15+
}

0 commit comments

Comments
 (0)