以下是两道非常经典的动态规划算法题,来自力口,解法也是老生常谈。然而,这两个在各自速度上排名第一的解决方案却很不寻常。先开个洞,待会再分析。LeetCode322ChangeChange给定不同面额的硬币和总金额。编写一个函数来计算最少需要多少个硬币来弥补总量。如果没有硬币组合构成总数,则返回-1。示例1:输入:coins=[1,2,5],amount=11输出:3解释:11=5+5+1示例2:输入:coins=[2],amount=3输出:-1解释:您可以认为每个硬币的数量是无限的。来源:LeetCode链接:https://leetcode-cn.com/probl...版权归LeetCode网络所有。商业转载请联系官方授权,非商业转载请注明出处。类解决方案(对象):defcoinChange(self,coins,amount):defdfs(idx,target,cnt):ifidx==len(coins):如果(target+coins[idx]-1)/coins[idx]+cnt>=self.ans:如果target%coins[idx]==0:self.ans=min(self.ans,cnt+target/coins[idx])returnforjinrange(target/coins[idx],-1,-1):dfs(idx+1,target-coins[idx]*j,cnt+j)self.ans=float('inf')coins=list(set(coins))硬币.sort(reverse=True)dfs(0,amount,0)return-1ifself.ans==float('inf')elseself.ansLeetCode72编辑距离给定两个单词word1和word2,计算word1的最小个数用于转换为word2的操作数。您可以对一个单词执行以下三种操作:插入一个字符删除一个字符替换一个字符示例1:输入:word1="horse",word2="ros"输出:3解释:horse->rorse(put'h'替换为'r')rorse->rose(删除'r')rose->ros(删除'e')示例2:输入:word1="intention",word2="execution"输出:5解释:intention->inention(删除't')inention->enention(将'i'替换为'e')enention->exention(将'n'替换为'x')exention->exection(将'n'替换为'c'')exection->execution(insert'u')来源:LeetCode链接:https://leetcode-cn.com/probl...CopyrightbelongstoLeetCode.商业转载请联系官方授权,非商业转载请注明出处。类解决方案:defminDistance(self,word1,word2):如果不是word1或不是word2:returnmax(len(word1),len(word2))stack1=[(0,0,0)]stack2=[(len(word1),len(word2),0)]mem1={}mem2={}whileTrue:newstack1=[]whilestack1:i,j,lv=stack1.pop()if(i,j)inmem2:returnlv+mem2[(i,j)]if(i,j)inmem1:continueelse:mem1[(i,j)]=lvifi
