LWC 53:691. Stickers to Spell Word

LWC 53:691. Stickers to Spell Word

传送门:691. Stickers to Spell Word

Problem:

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.

思路: 因为字母顺序无关,所以只需要统计target中每个字母出现的次数,接着对于给定的stickers,如果选择了某个sticker(当然你也可以不选),那么就从target中减去共同出现的字母频次(以sticker为准),这样一来,该问题就变成了重复子问题。

代码如下:

    static final int INF = 0x3f3f3f3f;
    Map<String, Integer> mem = new HashMap<>();

    int f(String target, int n) {
        if (mem.containsKey(target)) return mem.get(target);

        int[] tar = preprocess(target);
        int ans = INF;
        for (int i = 0; i < n; ++i) {

            StringBuilder sb = new StringBuilder();
            for (int j = 0; j < 32; ++j) {
                if (tar[j] > 0) {
                    for (int k = 1; k <= Math.max(0, tar[j] - sticker_map[i][j]); ++k) {
                        sb.append((char)(j + 'a'));
                    }
                }
            }

            String sub = sb.toString();

            if (sub.length() != target.length()) {
                ans = Math.min(ans, f(sub, n) + 1);
            }
        }
        mem.put(target, ans);
        return ans;
    }

    int[][] sticker_map;
    public int minStickers(String[] stickers, String target) {
        if (judge(stickers, target)) return -1;
        int n = stickers.length;
        sticker_map = new int[n][32];
        for (int i = 0; i < n; ++i) {
            sticker_map[i] = preprocess(stickers[i]);
        }
        mem.put("", 0);
        return f(target, n);
    }

    boolean judge(String[] stickers, String target) {
        int[] map = new int[32];
        for (char c : target.toCharArray()) {
            if (map[c - 'a'] == 0)
                map[c - 'a']++;
        }
        for (String s : stickers) {
            for (char c : s.toCharArray()) map[c - 'a'] --;
        }

        for (int i = 0; i < 32; ++i) {
            if (map[i] >= 1) return true;
        }
        return false;
    }

    int[] preprocess(String target) {
        int[] map = new int[32];
        for (char c : target.toCharArray()) map[c - 'a']++;
        return map;
    }

实际上是状态压缩DP,采用BOTTOM-UP,代码如下:

    public int minStickers(String[] stickers, String target) {
        int N = target.length();
        int[] dp = new int[1 << N];

        for (int i = 1; i < 1 << N; ++i) dp[i] = -1;

        for (int state = 0; state < 1 << N; ++state) {
            if (dp[state] == -1) continue;
            for (String sticker : stickers) {
                int now = state;
                for (char c : sticker.toCharArray()) {
                    for (int i = 0; i < N; ++i) {
                        if (((now >> i) & 1) == 1) continue;
                        if (c == target.charAt(i)) {
                            now |= 1 << i;
                            break;
                        }
                    }
                }

                if (dp[now] == -1 || dp[now] > dp[state] + 1) {
                    dp[now] = dp[state] + 1;
                }
            }
        }

        return dp[(1 << N) - 1];
    }

从递归的版本可以看出,前后状态发生变化的实际是target,HashMap记录的也是target各字符出现频次的【综合状态】,因此容易想到子问题出现与否只与target中每一位是否能被sticker构造相关(顺序无关),而target长度最大只有15位,因此可以用int数组表示当前位是否被选择,消耗内存O(1 << N).

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏Android 研究

APK安装流程详解3——PackageManager与PackageManagerService

上面一篇文章介绍了PackageManager,我们知道PackageManager是一个抽象类,它里面很重要的方法都是抽象的,所以在具体执行的时候,肯定是他的...

792
来自专栏非著名程序员

有效解决Android加载大图片内存溢出的问题

解决Android加载大图片内存溢出的问题 非著名程序员 ? 今天在交流群里,有人问我他经常遇到加载图片时内存溢出的问题,遇到的情况还是在自己的测试机或者...

2315
来自专栏魂祭心

原 大数运算

3275
来自专栏向治洪

android 自定义Lint

概述 Android Lint是Google提供给Android开发者的静态代码检查工具。使用Lint对Android工程代码进行扫描和检查,可以发现代码潜在的...

24410
来自专栏计算机视觉与深度学习基础

Leetcode 154 Find Minimum in Rotated Sorted Array II

Follow up for "Find Minimum in Rotated Sorted Array": What if duplicates are a...

1756
来自专栏数据之美

关于 hadoop reduce 阶段遍历 Iterable 的 2 个“坑”

之前有童鞋问到了这样一个问题:为什么我在 reduce 阶段遍历了一次 Iterable 之后,再次遍历的时候,数据都没了呢?可能有童鞋想当然的回答:Iter...

2156
来自专栏计算机视觉与深度学习基础

Leetcode 173 Binary Search Tree Iterator

mplement an iterator over a binary search tree (BST). Your iterator will be ini...

2016
来自专栏杂烩

Eclipse下Hadoop的MapReduce开发之MapReduce编写

    先说下业务需求吧,有个系统日志文件,记录系统的运行信息,其中包含DEBUG、INFO、WARN、ERROR四个级别的日志,现在想要看到所有级别各有多少条...

1159
来自专栏专知

关关的刷题日记09——Leetcode 80. Remove Duplicates from Sorted Array II

关小刷刷题09 – Leetcode 80. Remove Duplicates from Sorted Array II 方法1、2 题目 Follow up...

3228
来自专栏后端之路

Excel导入改善

最近由于上线的需要,对于excel导入导出的效率提出了要求。 那么一方面我们对于db落库的业务尽量走批量, 其次对于导入数据的校验以及对应成实体也做出了改善。...

3637

扫码关注云+社区