当前位置:网站首页>【LeetCode】 贴纸拼词(动态规划)
【LeetCode】 贴纸拼词(动态规划)
2022-07-28 13:46:00 【小七mod】
一、题目
我们有 n 种不同的贴纸。每个贴纸上都有一个小写的英文单词。
您想要拼写出给定的字符串 target ,方法是从收集的贴纸中切割单个字母并重新排列它们。如果你愿意,你可以多次使用每个贴纸,每个贴纸的数量是无限的。
返回你需要拼出 target 的最小贴纸数量。如果任务不可能,则返回 -1 。
注意:在所有的测试用例中,所有的单词都是从 1000 个最常见的美国英语单词中随机选择的,并且 target 被选择为两个随机单词的连接。
示例 1:
输入: stickers = ["with","example","science"], target = "thehat"
输出:3
解释:
我们可以使用 2 个 "with" 贴纸,和 1 个 "example" 贴纸。
把贴纸上的字母剪下来并重新排列后,就可以形成目标 “thehat“ 了。
此外,这是形成目标字符串所需的最小贴纸数量。
示例 2:
输入:stickers = ["notice","possible"], target = "basicbasic"
输出:-1
解释:我们不能通过剪切给定贴纸的字母来形成目标“basicbasic”。
提示:
- n == stickers.length
- 1 <= n <= 50
- 1 <= stickers[i].length <= 10
- 1 <= target.length <= 15
- stickers[i] 和 target 由小写英文单词组成
二、代码
class Solution {
public int minStickers(String[] stickers, String target) {
// 统计贴纸的词频 scount[i]表示第i张贴纸上每个字母的词频数量。这个题目和字符的排列顺序没关系,只和字符数量有关系
int[][] scount = new int[stickers.length][26];
for (int i = 0; i < stickers.length; i++) {
char[] tchars = stickers[i].toCharArray();
for (int j = 0; j < tchars.length; j++) {
scount[i][tchars[j] - 'a']++;
}
}
// 这里不能用目标字符串的词频统计来作为递归传参,因为dp是一个HashMap,它的key需要用一个对象唯一标识,只有字符串能做到这一点
// int[] tcount = new int[26];
// char[] targetChars = target.toCharArray();
// for (int i = 0; i < targetChars.length; i++) {
// tcount[targetChars[i] - 'a']++;
// }
HashMap<String, Integer> dp = new HashMap<>();
int min = process(scount, target, dp);
// 如果返回的是系统最大值,表示无法组成目标字符串
return min == Integer.MAX_VALUE ? -1 : process(scount, target, dp);
}
public int process(int[][] scount, String rest, HashMap<String, Integer> dp) {
// 如果已经有计算出来的结果了,就直接拿出来用
if (dp.containsKey(rest)) {
return dp.get(rest);
}
// 如果剩余的目标字符已经空了,就不需要贴纸了,直接返回0张贴纸
if (rest.length() == 0) {
return 0;
}
// 统计目标字符串的词频
int[] tcount = new int[26];
char[] targetChars = rest.toCharArray();
for (int i = 0; i < targetChars.length; i++) {
tcount[targetChars[i] - 'a']++;
}
int min = Integer.MAX_VALUE;
for (int i = 0; i < scount.length; i++) {
// 只有存在当前目标字符串中第一个字符的贴纸才会进入到递归分支。这个操作是剪枝优化,减少不必要的重复递归分支。这个操作并不印象最终结果,但是能减少递归分支数,提高执行效率
if (scount[i][targetChars[0] - 'a'] > 0) {
// 用贴纸的字符对目标字符串的字符进行冲减,并且生成新的目标字符串
StringBuilder sb = new StringBuilder();
for (int j = 0; j < 26; j++) {
int num = tcount[j] - scount[i][j];
// 注意,tcount是栈中的数据,下一次循环还要用呢,不能在这里就对其进行修改
//tcount[j] -= scount[i][j];
for (int k = 0; k < num; k++) {
sb.append((char) (j + 'a'));
}
}
String nextRest = sb.toString();
// 取最小值
min = Math.min(min, process(scount, nextRest, dp));
}
}
// 上面的循环中少算了每一个递归分支的第一个贴纸数,所以在这里要加1。如果min仍然为空,说明无法组合出目标字符串
min += (min == Integer.MAX_VALUE ? 0 : 1);
// 放入dp记录下来
dp.put(rest, min);
return min;
}
}三、解题思路
注意这道题目的每张贴纸都是无穷多的,想用多少张就用多少张,只要是可以拼出最后的目标字符串。所以这道题和字符的排列顺序无关,只和字符数量有关。
利用记忆化搜索,将计算好的结果存入到dp中,比肩重复计算。这道题在递归过程中用到了剪枝的技巧,减少不必要的递归分支,提高执行效率。
边栏推荐
- 如何有效进行回顾会议(上)?
- 用友BIP CRM新品发布,赋能大中型企业营销增长
- [utils] fastdfs tool class
- [translation] how to choose a network gateway for your private cloud
- Langjing Technology (Trax China) "robot +ai" opens the era of Chinese retail meta universe
- 树莓派基础 | 总结记录树莓派学习过程中的一些操作
- Install mysql5.7.36 in CentOS
- C语言实现简单学生成绩管理系统的方法
- Super resolution reconstruction based on deep learning
- Excel VBA 免密查看VBE加密代码
猜你喜欢

多所“双一流”大学,保研预报名启动!

UFIDA BiP CRM new product launch enables large and medium-sized enterprises to grow their marketing

Open source project - taier1.2 release, new workflow, tenant binding simplification and other functions

这3款在线PS工具,得试试

手机滚动截屏软件推荐
C # 7 methods to obtain the current path

Daily question - Scholarship

天气这么热太阳能发电不得起飞喽啊?喽啊个头……

朗镜科技(Trax中国)“机器人+AI”开启中国零售元宇宙时代

8、 Picker usage drop-down box selection effect
随机推荐
FormData对象的使用, var formdata=new FormData()
How to effectively conduct the review meeting (Part 1)?
Collaborative office tools: Online whiteboard is in its infancy, and online design has become a red sea
围绕新市民金融聚焦差异化产品设计、智能技术提效及素养教育
分集技术简略
[server data recovery] HP StorageWorks series server RAID5 offline data recovery of two disks
Realization of chat room function
Forage QR code -- online QR code generator
2022 melting welding and thermal cutting examination questions and online simulation examination
工厂模式和构造函数模式
As a programmer, how to manage time efficiently?
Recommended super easy-to-use mobile screen recording software
QQ robot configuration record based on nonebot2
Raspberry pie foundation | summarize and record some operations in the learning process of raspberry pie
ScottPlot入门教程:获取和显示鼠标处的数值
QML picture preview
多所“双一流”大学,保研预报名启动!
Unittest executes runtestcase prompt <_ io. Textiowrapper name= '< stderr>' mode=W encoding=UTF-8 > solution
Detailed explanation of common commands of vim (VIM use tutorial)
Why is it reverse to convert from other formats to BMP