LeetCode 691. Stickers to Spell Word
原题链接在这里:https://leetcode.com/problems/stickers-to-spell-word/
题目:
We are given N different types of stickers. Each sticker has a lowercase English word on it.
You would like to spell out the given target string by cutting individual letters from your collection of stickers and rearranging them.
You can use each sticker more than once if you want, and you have infinite quantities of each sticker.
What is the minimum number of stickers that you need to spell out the target? If the task is impossible, return -1.
Example 1:
Input:
["with", "example", "science"], "thehat"
Output:
3
Explanation:
We can use 2 "with" stickers, and 1 "example" sticker.
After cutting and rearrange the letters of those stickers, we can form the target "thehat".
Also, this is the minimum number of stickers necessary to form the target string.
Example 2:
Input:
["notice", "possible"], "basicbasic"
Output:
-1
Explanation:
We can't form the target "basicbasic" from cutting letters from the given stickers.
Note:
stickershas length in the range[1, 50].stickersconsists of lowercase English words (without apostrophes).targethas length in the range[1, 15], and consists of lowercase English letters.- In all test cases, all words were chosen randomly from the 1000 most common US English words, and the target was chosen as a concatenation of two random words.
- The time limit may be more challenging than usual. It is expected that a 50 sticker test case can be solved within 35ms on average.
题解:
For each sticker, count the char and corresponding multiplicity.
Have the DFS to check if target could be composed by these chars.
DFS state needs current target, stickers mapping, and memoization HashMap. memoization records minimization count for the target string.
If memoization contains current target, return the minimum count.
Otherwise, for each sticker, if sticker contains current target first char. Then use it and minus corresponding char multiplicity.
Get the base, if base != -1, update res with base + 1.
After trying each sticker, record the res.
Note: If the sticker doesn't contain current target first char, need to continue.
Otherwise, it would keep DFS with this sticker and go to DFS infinitely.
Time Complexity: exponential.
Space: exponential. memoization could be all the combination.
AC Java:
class Solution {
public int minStickers(String[] stickers, String target) {
if(target == null || stickers == null){
return 0;
}
int m = stickers.length;
int [][] map = new int[m][26];
for(int i = 0; i<m; i++){
for(char c : stickers[i].toCharArray()){
map[i][c - 'a']++;
}
}
HashMap<String, Integer> hm = new HashMap<>();
hm.put("", 0);
return dfs(map, target, hm);
}
private int dfs(int [][] map, String target, Map<String, Integer> hm){
if(hm.containsKey(target)){
return hm.get(target);
}
int [] tArr = new int[26];
for(char c : target.toCharArray()){
tArr[c - 'a']++;
}
int res = Integer.MAX_VALUE;
for(int i = 0; i<map.length; i++){
if(map[i][target.charAt(0) - 'a'] == 0){
continue;
}
StringBuilder sb = new StringBuilder();
for(int j = 0; j<26; j++){
if(tArr[j] > 0){
for(int k = 0; k<tArr[j] - map[i][j]; k++){
sb.append((char)('a' + j));
}
}
}
int base = dfs(map, sb.toString(), hm);
if(base != -1){
res = Math.min(res, base + 1);
}
}
res = res ==Integer.MAX_VALUE ? -1 : res;
hm.put(target, res);
return res;
}
}
LeetCode 691. Stickers to Spell Word的更多相关文章
- 691. Stickers to Spell Word
We are given N different types of stickers. Each sticker has a lowercase English word on it. You wou ...
- [LeetCode] Stickers to Spell Word 贴片拼单词
We are given N different types of stickers. Each sticker has a lowercase English word on it. You wou ...
- [Swift]LeetCode691. 贴纸拼词 | Stickers to Spell Word
We are given N different types of stickers. Each sticker has a lowercase English word on it. You wou ...
- LeetCode691. Stickers to Spell Word
We are given N different types of stickers. Each sticker has a lowercase English word on it. You wou ...
- Java for LeetCode 211 Add and Search Word - Data structure design
Design a data structure that supports the following two operations: void addWord(word)bool search(wo ...
- leetcode 题解: Length of Last Word
leetcode: Given a string s consists of upper/lower-case alphabets and empty space characters ' ', re ...
- leetcode@ [318] Maximum Product of Word Lengths (Bit Manipulations)
https://leetcode.com/problems/maximum-product-of-word-lengths/ Given a string array words, find the ...
- leetcode@ [211] Add and Search Word - Data structure design
https://leetcode.com/problems/add-and-search-word-data-structure-design/ 本题是在Trie树进行dfs+backtracking ...
- 【leetcode刷题笔记】Word Ladder II
Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from ...
随机推荐
- 动手学深度学习9-多层感知机pytorch
多层感知机 隐藏层 激活函数 小结 多层感知机 之前已经介绍过了线性回归和softmax回归在内的单层神经网络,然后深度学习主要学习多层模型,后续将以多层感知机(multilayer percetro ...
- 转载:string、const char*、 char* 、char[]相互转换
本文转自:https://blog.csdn.net/rongrongyaofeiqi/article/details/52442169 一:转化总结形式如下: 使用时,要对源格式和目标格式进行初始化 ...
- 明解C语言 入门篇 第六章答案
练习6-1 /* 求两个整数中的最小值 */ #include <stdio.h> /*--- 返回三个整数中的最小值 ---*/ int min2(int a, int b) { int ...
- [转帖]k8s 如何让你的应用活的更久
k8s 如何让你的应用活的更久 https://www.jianshu.com/p/132319e795ae 众所周知,k8s 可以托管你的服务 / 应用,当出现各种原因导致你的应用挂掉之后,k8s ...
- Dart:2.通过一个简单程序来理解Dart基础语法
一 . 一个简单的 Dart 程序 // 这是程序执行的入口. main() { var number = 42; // 定义并初始化一个变量. printNumber(number); // 调用一 ...
- 【spring boot】注解@Slf4j的使用
注解@Slf4j的使用 如果不想每次都写 private final Logger logger = LoggerFactory.getLogger(当前类名.class); 可以用注解@Slf4j ...
- 优化、分析Mysql表读写、索引等操作的sql语句效率优化问题
为什么要优化: 随着实际项目的启动,数据库经过一段时间的运行,最初的数据库设置,会与实际数据库运行性能会有一些差异,这时我们 就需要做一个优化调整. 数据库优化这个课题较大,可分为四大类: >主 ...
- C# Newtonsoft.Json JsonSerializerSettings配置序列化操作
https://blog.csdn.net/u011127019/article/details/72801033
- go 中string[0]到底是rune还是byte?
好像没区别,对吧? 来看个全面的对比: package main import ( "fmt" "reflect") func main(){ asci:=&q ...
- MySQL 分库分表及其平滑扩容方案
转自:https://kefeng.wang/2018/07/22/mysql-sharding/ 众所周知,数据库很容易成为应用系统的瓶颈.单机数据库的资源和处理能力有限,在高并发的分布式系统中,可 ...