leetcode

来源:互联网 发布:广西公务员待遇 知乎 编辑:程序博客网 时间:2024/05/29 09:14

Question 488 – Zuma Game

五种颜色:R(red)、Y(yellow)、W(white)、B(blue)、G(green)。
给定两个颜色字符串,名为board和hand。你每次需用hand中的一种颜色插入board中,使board中形成多于或等于3种相同的颜色连在一起,然后消除掉它们。给定的board颜色数不多于20,且board初始没有3个或更多相同颜色连在一起的。给定的hand颜色数不多于5。要求求出使board为空的最少插入的颜色数,若不能为空,则返回-1。

算法

用DFS思想。
1. 用一个vector(26)来统计hand中不同颜色的数量。
2. 消去board中3个或更多连在一起的相同颜色。
3. 若此时board为空,则返回0;
4. 遍历board,分别对于每个一个相同颜色的或两个相同颜色的进行消去,同时从hand中减掉需要插入的颜色,并返回所需插入颜色数量的最少值。对于消去后得到的每一个string返回步骤2,继续执行。
5. 遍历完后,返回需要插入的颜色数,注意颜色数初始赋值为6(因为hand中的总颜色数最多为5)。
6. 若返回的颜色数为6,则最终返回-1;否则返回需要的颜色数。

code

class Solution {public:    int findMinStep(string board, string hand) {        vector<int> handnums(26,0);        for(char ch: hand){            handnums[ch - 'A']++;        }        int steps = deffind(board, handnums);        return steps == 6 ? -1 : steps;     }    int deffind(string board, vector<int>& handnums){        board = removecommon(board);        if(board=="") return 0;        int steps = 6;//最多为5次        for (int i = 0; i < board.size(); i++){            int j = i;            while(board[j]==board[i]&&j<board.size()) j++;            int need = 3 - (j - i);            if(handnums[board[i]-'A']>=need){                handnums[board[i] - 'A'] -= need;                if(j<board.size()) steps = min(steps, need + deffind(board.substr(0, i) + board.substr(j), handnums));                else steps = min(steps, need + deffind(board.substr(0, i),handnums));                handnums[board[i] - 'A'] += need;            }            i = j - 1;        }        return steps;    }    string removecommon(string s){        //删除三个或三个以上连在一起的相同颜色        for (int i = 0; i < int(s.size()-1); i++){//当s.size()等于0时,减一后并不等于-1,因为size的返回类型是size_t,是8个字节的            int j = i;            while(s[j]==s[i]&&j<s.size()) j++;            if(j-i>=3){                if(j<s.size()) return removecommon(s.substr(0, i) + s.substr(j));                else return removecommon(s.substr(0,i));            }            else i = j - 1;        }        return s;    }};
原创粉丝点击