当前位置:网站首页>[leetcode] sticker spelling (dynamic planning)
[leetcode] sticker spelling (dynamic planning)
2022-07-28 14:39:00 【Xiaoqi Mod】
One 、 subject
We have n Different stickers . Each sticker has a small English word .
You want to spell the given string target , The method is to cut individual letters from the collected stickers and rearrange them . If you will , You can use each sticker multiple times , The number of each sticker is unlimited .
Back you need to spell target Minimum number of stickers . If the task is not possible , Then return to -1 .
Be careful : In all test cases , All the words are from 1000 A random selection of the most common American English words , also target Selected as a connection between two random words .
Example 1:
Input : stickers = ["with","example","science"], target = "thehat"
Output :3
explain :
We can use 2 individual "with" stickers , and 1 individual "example" stickers .
Cut and rearrange the letters on the sticker , You can form goals “thehat“ 了 .
Besides , This is the minimum number of stickers required to form the target string .
Example 2:
Input :stickers = ["notice","possible"], target = "basicbasic"
Output :-1
explain : We can't form goals by cutting the letters of a given sticker “basicbasic”.
Tips :
- n == stickers.length
- 1 <= n <= 50
- 1 <= stickers[i].length <= 10
- 1 <= target.length <= 15
- stickers[i] and target Made up of lowercase English words
Two 、 Code
class Solution {
public int minStickers(String[] stickers, String target) {
// Count the word frequency of stickers scount[i] It means the first one i The number of word frequencies of each letter on the poster . This topic has nothing to do with the order of characters , Only related to the number of characters
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']++;
}
}
// Here, the word frequency statistics of the target string cannot be used as recursive parameters , because dp It's a HashMap, its key You need to use an object to uniquely identify , Only strings can do this
// 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);
// If the maximum value of the system is returned , Indicates that the target string cannot be formed
return min == Integer.MAX_VALUE ? -1 : process(scount, target, dp);
}
public int process(int[][] scount, String rest, HashMap<String, Integer> dp) {
// If there are already calculated results , Just take it out and use it
if (dp.containsKey(rest)) {
return dp.get(rest);
}
// If the remaining target characters are empty , There is no need for stickers , Go straight back to 0 Post paper
if (rest.length() == 0) {
return 0;
}
// Count the word frequency of the target string
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++) {
// Only the sticker with the first character in the current target string will enter the recursive Branch . This operation is pruning optimization , Reduce unnecessary repeated recursive branches . This operation does not impress the final result , But it can reduce the number of recursive branches , Improve execution efficiency
if (scount[i][targetChars[0] - 'a'] > 0) {
// Offset the characters of the target string with the characters of the sticker , And generate a new target string
StringBuilder sb = new StringBuilder();
for (int j = 0; j < 26; j++) {
int num = tcount[j] - scount[i][j];
// Be careful ,tcount Is the data in the stack , I'll use it again in the next cycle , It cannot be modified here
//tcount[j] -= scount[i][j];
for (int k = 0; k < num; k++) {
sb.append((char) (j + 'a'));
}
}
String nextRest = sb.toString();
// Minimum value
min = Math.min(min, process(scount, nextRest, dp));
}
}
// In the above loop, the number of the first sticker of each recursive branch is underestimated , So we need to add 1. If min Still empty , Description the target string cannot be combined
min += (min == Integer.MAX_VALUE ? 0 : 1);
// Put in dp recorded
dp.put(rest, min);
return min;
}
}3、 ... and 、 Their thinking
Note that each sticker on this topic is infinite , Use as many as you want , As long as it can spell the final target string . So this question has nothing to do with the order of characters , Only related to the number of characters .
Use memory search , Store the calculated results in dp in , Shoulder to shoulder double counting . This problem uses pruning skills in the recursive process , Reduce unnecessary recursive branches , Improve execution efficiency .
边栏推荐
- OKR and grad
- How did Dongguan Huawei cloud data center become a new model of green data center?
- Leetcode 0142. circular linked list II
- Floating point data type in C language (did you learn to waste it)
- 468产品策划与推广方案(150份)
- 9、 Uni popup usage popup effect at the bottom of the drop-down box
- How to effectively conduct the review meeting (Part 1)?
- unittest执行runTestCase提示<_io.TextIOWrapper name=‘<stderr>‘ mode=‘w‘ encoding=‘utf-8‘>解决方案
- 天气这么热太阳能发电不得起飞喽啊?喽啊个头……
- ScottPlot入门教程:获取和显示鼠标处的数值
猜你喜欢
![[ecmascript6] async and await](/img/3c/c7de42ad572dc95b188243c02dd228.png)
[ecmascript6] async and await

These three online PS tools should be tried

十、时间戳

Many "double first-class" universities have launched the research guarantee and prediction name!

How to reduce the resolution of only 3D camera but not UI camera
C # read INI file and key value pair operation

草料二维码--在线二维码生成器

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

2022 melting welding and thermal cutting examination questions and online simulation examination

ScottPlot入门教程:获取和显示鼠标处的数值
随机推荐
爆肝整理JVM十大模块知识点总结,不信你还不懂
How to effectively conduct the review meeting (Part 1)?
为 @CloudStorage 添加了类 @Published 的能力
What is gossip (E-Net gossip)
Core Data 是如何在 SQLite 中保存数据的
Database optimization understanding these is enough
实时切换 Core Data 的云同步状态
10、 Timestamp
如何有效进行回顾会议(上)?
Tdengine helps Siemens' lightweight digital solutions
Floating point data type in C language (did you learn to waste it)
Minitest -- applet automation testing framework
Leetcode 1331. array sequence number conversion
9、 Uni popup usage popup effect at the bottom of the drop-down box
Xcode编写SwiftUI代码时一个编译通过但导致预览(Preview)崩溃的小陷阱
UFIDA BiP CRM new product launch enables large and medium-sized enterprises to grow their marketing
Install mysql5.7.36 in CentOS
AFNetworking速成教程
Why is it reverse to convert from other formats to BMP
一些企业数据平台建设的思考