leetcode

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;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值