algorithm - 如何在这个递归解决方案中添加记忆来拼写单词
问题描述
我正在尝试解决https://leetcode.com/problems/stickers-to-spell-word/
我想出了下面的递归解决方案
class Solution {
public int minStickers(String[] stickers, String target) {
int[] arr = new int[26];
for(int i = 0 ; i <26;++i) {
arr[i]=0;
}
int len = target.length();
for(int i = 0 ; i < len; ++i) {
arr[target.charAt(i)-'a']++;
}
int lenS= stickers.length;
Integer ans = cal( stickers, 0,arr, 0,len);
if(ans==Integer.MAX_VALUE) {
return -1;
}
return ans;
}
public int cal(String[] stickers, int pos, int[] arr, int count, int totalLen) {
int[] mp = arr.clone();
int curTotalLen=totalLen;
int didChange=0;
if(pos<stickers.length) {
for(int i = 0 ; i < stickers[pos].length(); ++i) {
if(mp[stickers[pos].charAt(i)-'a'] > 0) {
mp[stickers[pos].charAt(i)-'a']--;
--curTotalLen;
didChange=1;
}
}
if(curTotalLen<=0) {
return (count+didChange);
}
if(didChange==1) {
return Math.min(cal(stickers,pos,mp,count+didChange,curTotalLen),
cal(stickers,pos+1,arr,count,totalLen));
}
return cal(stickers,pos+1,arr,count,totalLen);
}
return Integer.MAX_VALUE;
}
}
我无法向这个递归解决方案添加记忆。我知道网上有很多针对这个问题的解决方案,但我想在我能想到的这个特定解决方案中添加moemoization。因此,我的解决方案所做的就是在每一步都对当前单词和下一个单词进行递归。如果当前单词不能减少目标中的字符数,那么它将不会为它递归,否则它将为它递归。(在我用尽所有的stcikers之前,它总是会递归下一个贴纸)
解决方案
推荐阅读
- c# - 当另一个表单关闭时显示一个表单
- c# - FSCalendar Xamarin:如何更改日期标签标题?
- nunit-3.0 - 单独运行测试用例 Nunit Console Runner
- material-ui - Material UI (v1.0) : 为 TextField 强制换行
- javascript - 在 JavaScript ForEach 中更新迭代数组
- firebase - Firebase 动态链接 | 短链接不会直接在手机上打开
- php - Linux pdoprepared statement utf-8 issue
- canvas - 如何 v-for 驱动画布标签并将内容保存在画布中
- javascript - Apps 脚本不比较 if 语句中的 2 个值
- python - 如何为我的数据选择最佳匹配模式(单倍型)?蟒蛇 2.7