算法每日一题
Posted Rgylin
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了算法每日一题相关的知识,希望对你有一定的参考价值。
文章目录
题目描述
You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.
Return the number of combinations that make up that amount. If that amount of money cannot be made up by any combination of the coins, return 0.
You may assume that you have an infinite number of each kind of coin.
The answer is guaranteed to fit into a signed 32-bit integer.
简单来说就是:=>
你有一组整形的数组代表不同的数值,还有一个总的钱数,返回这个所能买的组合数
力扣(LeetCode)
链接:https://leetcode-cn.com/problems/coin-change-2
Input: amount = 5, coins = [1,2,5]
Output: 4
Explanation: there are four ways to make up the amount:
5=5
5=2+2+1
5=2+1+1+1
5=1+1+1+1+1
利用回溯
一看就是排列组合问题,上才艺
path=[]
result=[]
def backTo(s,startIndex,t):
if(sum(path)==t):
result.append(path[:])
return
if(sum(path)>t):
return
for i in range(startIndex,len(s)):
path.append(s[i])
backTo(s,i,t)
path.pop()
一顿操作发现直接给超时了
那就利用动态规划
- 确定dp表示的含义: 下标j 数量为j时所能组成的最大数目
- 确定dp 推导公式: dp[j]为 此物品没放时最大数目,即:dp[j-num[i]]因为加了nums[i]就达到了dp[j]
- 初始化dp[0]=1 其他为0
代码为
amount = 5
coins = [1,2,5]
dp=( amount+1)*[0]
dp[0]=1
for i in range(len(coins)):
for j in range(coins[i],amount+1):
dp[j]+=dp[j-coins[i]]
print(dp)
简单几行代码就解决了,是不是很强大
以上是关于算法每日一题的主要内容,如果未能解决你的问题,请参考以下文章