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

    解答:

    https://discuss.leetcode.com/topic/106273/c-java-python-dp-memoization-with-optimization-29-ms-c

    There are potentially a lot of overlapping sub problems, but meanwhile we don't exactly know what those sub problems are. DP with memoization works pretty well in such cases. The workflow is like backtracking, but with memoization. Here I simply use a sorted string of target as the key for the unordered_map DP. A sorted target results in a unique sub problem for possibly different strings.

    dp[s] is the minimum stickers required for string s (-1 if impossible). Note s is sorted.
    clearly, dp[""] = 0, and the problem asks for dp[target].
    

    The DP formula is:

    dp[s] = min(1+dp[reduced_s]) for all stickers, 
    here reduced_s is a new string after certain sticker applied
    

    Optimization: If the target can be spelled out by a group of stickers, at least one of them has to contain character target[0]. So I explicitly require next sticker containing target[0], which significantly reduced the search space.


    代码:

    class Solution {

    public:
        int minStickers(vector<string>& stickers, string target) {
            vector<vector<int>> stick(stickers.size(),vector<int>(26,0));     
            for(int i=0;i<stickers.size();i++)
            {
                for(char c:stickers[i])
                {
                    stick[i][c-'a']++;
                }
            }
            
            unordered_map<string,int> dp; 
            dp[""]=0;
            return helper(stick,target,dp);
            
        }
        
    private:
        int helper(vector<vector<int>>& stick, string target,unordered_map<string,int> &dp) {
            if(dp.count(target)) return dp[target];//if there is a ans in dp, return the memory value
            int ans=INT_MAX;
            
            vector<int> tar(26,0);    
            for(char c:target)
            {
                tar[c-'a']++;          
            }
            
            //if stick has first chatacter of target, apply it.
            for(int i=0;i<stick.size();i++)
            {
                if(stick[i][target[0]-'a'] == 0) continue;
                
                string s;//s is characters target left after using a stick.
                for(int j=0;j<26;j++)
                    if(tar[j]-stick[i][j]>0) s += string(tar[j]-stick[i][j],j+'a');
                
                if(s.size()<target.size())
                {
                    int tmp = helper(stick,s,dp);
                    if(tmp!=-1) ans=min(ans,tmp+1);//if taret can be put together 
                }
            }
            
            dp[target] = ans == INT_MAX ? -1 : ans;
            return dp[target];
        }   


    };
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值