DP 人生第一道Hard,不出意外没做出来(详细注释,安慰一下自己)

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

  思路上其实并不难,比较容易想到可以用DP方向的解法。
  用若干stickers组成target,有点类似背包问题。区别有如下几点:
  1. stickers任意种类不限数量,可重复
  2. 每一个sticker都只是选取其中一部分,而不是全部
  3. 组成目标target固定,缺一个字母都不可

  那么接下来分析DP必须的4大要素:

  • 子问题分解,独立
    • 子问题分解:可以遍历去掉每一个sticker的情况;
    • 子问题独立:从target中去掉某一个sticker可以提供的内容,剩下的‘target’依旧是可以通过所有stickers构成。
  • 最优子结构
    • 使用sticker数量最少的。
  • 边界
    • 可以组成:剩余target为""
    • 无法组成:剩余target需要的字母,support一个都提供不了;
  • 备忘录
    • 考虑dp数组(dp的数据结构根据需要自行选取,不一定是数组)里面要存什么东西,保证可以节省重复计算;
    • 一般来说,dp数组里存的都是目标结果,那么这里就应存 target 及其所需 sticker 数量,因此dp的数据结构选取 Map 比较合适。

代码如下:

public int minStickers(String[] stickers, String target) {
    int m = stickers.length;
    int[][] mp = new int[m][26];//存每一个sticker可以提供的字母及其数量
    Map<String, Integer> dp = new HashMap<>();//dp数据结构,表明对每一个目标target,需要几根stickers
    for (int i = 0; i < m; i++) 
        for (char c:stickers[i].toCharArray()) mp[i][c-'a']++;
    dp.put("", 0);//成功边界:剩余target为 ""
    return helper(dp, mp, target);//返回值即是目标为 target 时的结果,这样该函数对任意 target 都可以使用
}

private int helper(Map<String, Integer> dp, int[][] mp, String target) {

    //备忘录,每完成一个target,都记录下来,以供后续使用,避免重复计算
    if (dp.containsKey(target)) return dp.get(target);

    int ans = Integer.MAX_VALUE, n = mp.length;
    int[] tar = new int[26];
    for (char c:target.toCharArray()) tar[c-'a']++;

    // try every sticker
    for (int i = 0; i < n; i++) {

        // optimization 失败边界(关键)
        //对于一个新的target,它所需要的其中一个字符如果在mp[i][]里面没有,那就不需要再看mp[i][]了,
        //因为最终为了组成target是一定要[target.charAt(0)-'a']的,而mp[i]里没有,所以直接continue即可。 
        //并且只要每次都是按此判断进行 continue,就不会遗漏正确的组成方案。
        if (mp[i][target.charAt(0)-'a'] == 0) continue;

        StringBuilder sb = new StringBuilder();
        // apply a sticker on every character a-z
        for (int j = 0; j < 26; j++) {
            if (tar[j] > 0 ) 
                //从本轮target中去掉一个mp[i][]中可以提供的字母,同时将剩下的按序组成一个String,
                //作为下一轮的target使用
                for (int k = 0; k < Math.max(0, tar[j]-mp[i][j]); k++)
                    sb.append((char)('a'+j));
        }
        String s = sb.toString();
        int tmp = helper(dp, mp, s);

        //若返回的是-1,说明这一轮用mp[i]的路线失败,继续看使用mp[i+1]的情况
        //返回的不是-1,就看这一轮用mp[i]的结果ans是否比之前的要好了
        if (tmp != -1) ans = Math.min(ans, 1+tmp);
    }

    //如果无法组成,即每一次if (mp[i][target.charAt(0)-'a'] == 0) continue;都执行了,
    //则ans依旧为Integer.MAX_VALUE,应当返回-1,表示无法组成
    //如果有可以成功组成target的方案,则将当前target存入dp,并返回ans
    dp.put(target, ans == Integer.MAX_VALUE? -1:ans);
    return dp.get(target);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值