原题链接在这里: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. Qt 编写串口调试助手

    一.成品图展示 成品图如下所示: 二.串口通讯步骤 1.在工程文件(.pro)中添加串口通信相关运行库:QT += serialport 2.在头文件中添加: #include <QSerial ...

  2. Shell脚本——显示系统上的登录用户数

    写一个脚本showlogged.sh,其用法格式为: showlogged.sh -v -c -h|--help 其中,-h选项只能单独使用,用于显示帮助信息:-c选项时,显示当前系统上登录的所有用户 ...

  3. OpenCV vs. Armadillo vs. Eigen on Linux

    OpenCV vs. Armadillo vs. Eigen on Linux From:http://nghiaho.com/?p=936 In this post I’ll be comparin ...

  4. AtomicInteger例子

    AtomicInteger可以保证原子性,可见性,有序性 public class AtomicIntegerTest { private static AtomicInteger value = n ...

  5. Redis Persistent Replication Sentinel Cluster的一些理解

    Redis Persistent Replication Sentinel Cluster的一些理解 我喜欢把工作中接触到的各种数据库叫做存储系统,笼统地说:Redis.Mysql.Kafka.Ela ...

  6. 【CF285E】Positions in Permutations(动态规划,容斥)

    [CF285E]Positions in Permutations(动态规划,容斥) 题面 CF 洛谷 题解 首先发现恰好很不好算,所以转成至少,这样子只需要确定完一部分数之后剩下随意补. 然后套一个 ...

  7. SQLServer之服务器连接

    目录 SQL Server Management Studio连接 CMD命令行窗口连接 通用数据连接文件连接 SQL Server Management Studio连接 定义 SQL Server ...

  8. List和模型学完后的练习

    概述:控制台程序,sqlserver数据库,库D1,表T1. 学生信息表: 表结构: 其中id自动编号. 主程序先完成框架,循环录入选项进行操作: namespace ConsoleApplicati ...

  9. 北理工机器人队RM视觉组学习参考汇总(持续更新中)

    欢迎大家有意加入北理工机器人队参与到视觉组的工作中.在大家能够正式作为队员参与到视觉组的准备工作之前,北理机器人队需要对各位进行培训.这篇文章主要面向有志于参加机器人队视觉组的同学.同时,欢迎所有对相 ...

  10. Matlab混入模式(Mixin)

    Mixin是一种类,这种类包含了其他类要使用的特性方法,但不必充当其他类的父类.Matlab无疑是支持多继承的.我们可以利用 Matlab 的这种特性,实现一种叫做 Mixin 的类.MixIn的目的 ...