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;
}
};