/*
难度:中等
给定不同面额的硬币和一个总金额,写出函数来计算可以凑成总金额的硬币组合数。
假设每种面额的硬币有无限个。
示例:
输入 coins=[1,2,5], amount=5
输出 4
5=5; 5=2+2+1; 5=2+1+1+1; 5=1+1+1+1+1
假定:
0 <= amount <= 5000; 1 <= 面额 <= 5000
硬币种类不超过500种; 结果符合32位符号整数
*/
extension Daily {
static func test_leetcode518() {
//不能有重复的面额
// let coins = [1,2,5]; let amount = 15
let coins = [2,7,13]; let amount = 500
let res = Daily.leetcode518(coins, amount)
print("最终结果 \(res)")
}
static func leetcode518(_ coins: [Int], _ amount: Int) -> Int {
if amount < 1 {
print("amount is 0")
return 1
}
if coins.count < 1 {
print("coins is empty")
return 0
}
var thisLine = Array(repeating: 0, count: amount + 1);
thisLine[0] = 1
for idx1 in 0..<coins.count {
let current = coins[idx1]
if current > amount {
continue
}
thisLine[current] += 1
var j = current + 1
while j <= amount {
thisLine[j] = thisLine[j] + thisLine[j - current]
j += 1
}
}
return thisLine.last!
}
static func leetcode518_2(_ coins: [Int], _ amount: Int) -> Int {
var icoins = coins;
if amount < 1 {
print("amount is 0")
return 1
}
if icoins.count < 1 {
print("coins is empty, or amount is 0")
return 0
}
icoins.insert(0, at: 0)
let count = icoins.count
let maxtime = amount + 1 //第一行都是0
var map = Array(repeating: 0, count: count*maxtime);
for idx in 1..<icoins.count {
map[(idx-1)*maxtime] = 1;
}
for idx1 in 1..<icoins.count {
let current = icoins[idx1]
for j in 1...amount {
let coor = idx1*maxtime + j
if j < current {
map[coor] = map[(idx1-1)*maxtime + j]
}
else {
let times = j / current
var sum = map[(idx1-1)*maxtime + j]
for num in 1...times {
sum += map[(idx1-1)*maxtime + j - num*current]
}
map[coor] = sum
}
}
}
// for i in 0..<count {
// for j in 0..<maxtime {
// print("\(map[i*maxtime + j]) ", separator: " ", terminator: "")
// }
// print("")
// }
return map[count*maxtime-1]
}
}
【LeetCode 518】零钱兑换 II
最新推荐文章于 2024-07-14 09:27:48 发布