Think about Zuma Game. You have a row of balls on the table, colored red(R), yellow(Y), blue(B), green(G), and white(W). You also have several balls in your hand.
Each time, you may choose a ball in your hand, and insert it into the row (including the leftmost place and rightmost place). Then, if there is a group of 3 or more balls in the same color touching, remove these balls. Keep doing this until no more balls can be removed.
Find the minimal balls you have to insert to remove all the balls on the table. If you cannot remove all the balls, output -1.
Examples:
Input: “WRRBBW”, “RB”
Output: -1
Explanation: WRRBBW -> WRR[R]BBW -> WBBW -> WBB[B]W -> WW
Input: “WWRRBBWW”, “WRBRW”
Output: 2
Explanation: WWRRBBWW -> WWRR[R]BBWW -> WWBBWW -> WWBB[B]WW -> WWWW -> empty
Input:”G”, “GGGGG”
Output: 2
Explanation: G -> G[G] -> GG[G] -> empty
Input: “RBYYBBRRB”, “YRBGB”
Output: 3
Explanation: RBYYBBRRB -> RBYY[Y]BBRRB -> RBBBRRB -> RRRB -> B -> B[B] -> BB[B] -> empty
题意很简单,就是类似消消乐的游戏,想了很久还是不会做,看了一下网上的教程,做得方法真的帮,就是一个递归搜索,
这道题很值得学习
代码如下:
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <string>
#include <climits>
#include <algorithm>
#include <sstream>
#include <functional>
#include <bitset>
#include <numeric>
#include <cmath>
using namespace std;
#define MAX_STEP 6
class Solution
{
public:
int findMinStep(string board, string hand)
{
sort(hand.begin(),hand.end());
int res = dfs(board,hand);
return res > hand.size() ? -1 : res;
}
int dfs(string b,string h)
{
if (b.size() <= 0)
return 0;
else if (h.size() <= 0)
return MAX_STEP;
else
{
int res = MAX_STEP;
for (int i = 0; i < h.size(); i++)
{
int j = 0;
while (j < b.size())
{
int k = b.find(h[i],j);
if (k == b.npos)
break;
if (k < b.size() - 1 && b[k] == b[k + 1])
{
string nextb = shrink(b.substr(0, k) + b.substr(k + 2));
if (nextb.size() <= 0)
return 1;
string nexth = h;
nexth.erase(i,1);
res = min(res,dfs(nextb,nexth)+1);
k++;
}
else if (i > 0 && h[i] == h[i - 1])
{
string nextb = shrink(b.substr(0, k) + b.substr(k + 1));
if (nextb.size() <= 0)
return 2;
string nexth = h;
nexth.erase(i, 1);
nexth.erase(i-1, 1);
res = min(res, dfs(nextb, nexth) + 2);
}
j = k + 1;
}
}
return res;
}
}
string shrink(string s)
{
while (s.size() > 0)
{
bool done = true;
int start = 0;
for (int i = 0; i <= s.size(); i++)
{
if (i == s.size() || s[i] != s[start])
{
if (i - start >= 3)
{
s = s.substr(0, start) + s.substr(i);
done = false;
break;
}
start = i;
}
}
if (done == true)
break;
}
return s;
}
};