2020-5 leetcode 488. 祖玛游戏

1.用的方法很笨,就是一个球一个球的去DFS 遍历。
2.需要借鉴的是,所有的剪枝函数是怎么写出来。(要自己去预想,基于所需的参数去预想)
3.对于消除重复串的递归函数boom的写法要注意。以及对于一些无用情况的避免的一些操作。

class Solution {
public:
    int ans;
    string boom(string s,int i){
        if(s.empty()) return "";
        int left=i,right=i;
        while(left>0&&s[left-1]==s[left]) --left;
        while(right<s.size()-1&&s[right+1]==s[right]) ++right;
        if(right-left+1>=3){
            s=s.substr(0,left)+s.substr(right+1);
            return boom(s,max(left-1,0));
        }
        return s;
    }
    void DFS(string pB,map<char,int>& handCount,int usedcount,int remain){
        if(pB.empty()) ans=min(ans,usedcount);
        else{
            if(remain==0||usedcount+1>=ans) return;
            else{
                map<char,int> pBcount;
                for(char x:pB){
                    pBcount[x]++;
                }
                int nextste=0;
                for(auto p:pBcount){
                    if(p.second<3){
                        nextste+=3-p.second;
                    }
                    if((3-p.second)>handCount[p.first]) return;
                }
                if((nextste+usedcount)>=ans) return;
                for(auto h:handCount){
                    if(h.second==0) continue;
                    char choose=h.first;
                    if(!pBcount.count(choose)) continue;
                    for(int i=0;i<pB.size();i++){
                        if(i>0&&choose==pB[i-1]) continue;
                        string tmp=pB;
                        tmp.insert(tmp.begin()+i,choose);
                        tmp=this->boom(tmp,i);
                        handCount[choose]--;
                        DFS(tmp,handCount,usedcount+1,remain-1);
                        handCount[choose]++;
                    }
                    if(choose==pB.back()) continue;
                    string tmp=pB;
                    tmp.push_back(choose);
                    handCount[choose]--;
                    DFS(tmp,handCount,usedcount+1,remain-1);
                    handCount[choose]++;
                }


            }
        }
    }
    int findMinStep(string board, string hand) {
        ans = INT_MAX;
        map<char,int>handCount;
        for(const auto& h:hand) handCount[h]++;
        DFS(board,handCount,0,hand.size());
        return ans==INT_MAX?-1:ans;
    }
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值