原题链接在这里: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:

  • stickers has length in the range [1, 50].
  • stickers consists of lowercase English words (without apostrophes).
  • target has 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的更多相关文章

  1. 691. Stickers to Spell Word

    We are given N different types of stickers. Each sticker has a lowercase English word on it. You wou ...

  2. [LeetCode] Stickers to Spell Word 贴片拼单词

    We are given N different types of stickers. Each sticker has a lowercase English word on it. You wou ...

  3. [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 ...

  4. LeetCode691. Stickers to Spell Word

    We are given N different types of stickers. Each sticker has a lowercase English word on it. You wou ...

  5. 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 ...

  6. leetcode 题解: Length of Last Word

    leetcode: Given a string s consists of upper/lower-case alphabets and empty space characters ' ', re ...

  7. 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 ...

  8. leetcode@ [211] Add and Search Word - Data structure design

    https://leetcode.com/problems/add-and-search-word-data-structure-design/ 本题是在Trie树进行dfs+backtracking ...

  9. 【leetcode刷题笔记】Word Ladder II

    Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from ...

随机推荐

  1. java识别死亡或者存活的对象

    那些内存需要回收 内存回收是对运行时内存区域的内存回收,其中程序计数器.虚拟机栈.本地方法栈3个区域随线程而生,随线程而灭:栈中的栈帧随着方法的进入和退出而有条不紊的执行着出栈和入栈操作.每一个栈帧中 ...

  2. HTTP之缓存处理步骤

    缓存的处理步骤 =================摘自<HTTP权威指南>===================== 现代的商业化代理缓存相当的复杂.这些缓存构建的非常有效,可以支持HTT ...

  3. 动态引用存储——集合&&精确的集合定义——泛型

    1,集合宏观理解 1.1,为什么引入集合? 对于面向对象的语言来说,操作对象的功能不可或缺. 为了方便对对象进行操作和处理,就必须要对对象进行暂时的存储.[数据最终存在数据库里] 使用数组来存储对象的 ...

  4. 中文情感分析——snownlp类库 源码注释及使用

    最近发现了snownlp这个库,这个类库是专门针对中文文本进行文本挖掘的. 主要功能: 中文分词(Character-Based Generative Model) 词性标注(TnT 3-gram 隐 ...

  5. CycleBarrier与CountDownLatch原理

    CountDownLatch 众所周知,它能解决一个任务必须在其他任务完成的情况下才能执行的问题,代码层面来说就是只有计数countDown到0的时候,await处的代码才能继续向下运行,例如: im ...

  6. Java 常用知识点汇总(数据类型之间转换、字符串的相关操作-截取、转换大小写等)

    1.Java四类八种数据类型 byte:Java中最小的数据类型,在内存中占8位(bit),即1个字节,取值范围-128~127,默认值0 short:短整型,在内存中占16位,即2个字节,取值范围- ...

  7. 乘法器——booth编码

    博主最近在学习加法器.乘法器.IEEE的浮点数标准,作为数字IC的基础.当看到booth编码的乘法器时,对booth编码不是很理解,然后在网上找各种理解,终于豁然开朗.现将一个很好的解释分享给大家,希 ...

  8. [转] console.log的高级用法

    //基本用法 console.log('最常见用法\n换行'); console.error('输出错误信息 会以红色显示'); console.warn('打印警告信息 会以黄色显示'); cons ...

  9. hadoop格式化:java.io.IOException: Incompatible clusterIDs in /home/lxh/hadoop/hdfs/data: namenode clusterID

    1 概述  解决hadoop启动hdfs时,datanode无法启动的问题.错误为: java.io.IOException: Incompatible clusterIDs in /home/lxh ...

  10. SpringBoot嵌入式Tomcat的自动配置原理

    在读本篇文章之前如果你读过这篇文章SpringBoot自动装配原理解析应该会更加轻松 准备工作 我们知道SpringBoot的自动装配的秘密在org.springframework.boot.auto ...