【LeetCode 518】零钱兑换 II

15 篇文章 0 订阅
/*
难度:中等
给定不同面额的硬币和一个总金额,写出函数来计算可以凑成总金额的硬币组合数。
假设每种面额的硬币有无限个。

示例:
输入 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]
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值