topic
Thinking
To solve two problems:
- How to determine the position eliminated. Through i, j subscripts identify the two different color boundaries, eliminating the need to determine the number of balls. For example RRWRR, when i = 0, increasing j, until j = 2, this time eliminating the need RR 3 - (j - i) = 1. However, a problem arises, that is, there will be continuous elimination, e.g. RRRR at this time, when traversed, i = 0, j = 4, this time 3- (ji) = - 1. In this case traverse time to pay attention.
- Successive Elimination to find the problems such as RRWWR.
Code
class Solution {
public:
int DFS(string board,map<char,int> num){
if(board.empty()) return 0;
int ans = 0x3f3f3f3f,l = board.length(),need,i,j;
for(i = 0;i < l;i = j){
j = i + 1;
while(j < l && board[j] == board[i]) j++;
need = 3 - (j - i);//当前位置要满足三个球消除需要几个额外的。
if(need <= num[board[i]]){
need = max(0,need);//可能存在有连续消除的情况。此时need为负数。例如WWWW
num[board[i]] -= need;
string subStr = board.substr(0,i) + board.substr(j);
int cnt = DFS(subStr,num);
if(cnt >= 0)
ans = min(ans , need + cnt);
num[board[i]] += need;
}
}
if(ans == 0x3f3f3f3f) return -1;
else return ans;
}
int findMinStep(string board, string hand) {
map <char,int> num;//这里要定义char
num['R']=num['Y']=num['B']=num['G']=num['W']=0;
int l = hand.length();
for(int i = 0;i < l;i++){
num[hand[i]]++;
}
return DFS(board,num);
}
};