Java implementation LeetCode 691 stickers Spelling (DFS + map records)

691. stickers Spelling

We are given N different types of stickers. We have a lowercase English words on each sticker.

You want to cut a single letter and rearrange their own stickers from the collection, which spell out a given target string target.

If you wish, you can use more than once per a sticker and a sticker each number is unlimited.

The minimum number of stickers to spell out how much is needed to target target? If the task is impossible, -1 is returned.

Example 1:

Input:

[ "With", "example" , "science"], "thehat"
output:

3
explanation:

We can use two "with" sticker, and an "example" sticker.
After the letters on the label cut out and re-arranged form certain "thehat" a.
Moreover, this is the minimum number required to form a target string of the sticker.
Example 2:

Input:

[“notice”, “possible”], “basicbasic”
输出:

-1
explanation:

We can not cut stickers to the letters given to form the target "basicbasic".

prompt:

stickers length range [1, 50].
stickers lowercase English-word (with no apostrophe).
the length of the target in the range [1, 15], lowercase letters.
In all test cases, all the words are from the 1000 most common American English words randomly selected, the goal is a series of two random words.
Time limits may be more challenging than usual. 50 is expected to average sticker test cases can be resolved within 35ms.

class Solution {
   public int minStickers(String[] stickers, String target) {
        int m = stickers.length;
        int[][] mp = new int[m][26];
        Map<String, Integer> dp = new HashMap<>();
        for (int i = 0; i < m; i++)
            for (char c : stickers[i].toCharArray()) mp[i][c - 'a']++;
        dp.put("", 0);
        return helper(dp, mp, target);
    }

    private int helper(Map<String, Integer> dp, int[][] mp, String 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']++;
        for (int i = 0; i < n; i++) {
            if (mp[i][target.charAt(0) - 'a'] == 0) continue;
            StringBuilder sb = new StringBuilder();
            for (int j = 0; j < 26; j++) {
                if (tar[j] > 0)
                    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);
            if (tmp != -1) ans = Math.min(ans, 1 + tmp);
        }
        dp.put(target, ans == Integer.MAX_VALUE ? -1 : ans);
        return dp.get(target);
    }
}
Released 1740 original articles · won praise 30000 + · views 3.67 million +

Guess you like

Origin blog.csdn.net/a1439775520/article/details/105330444