Leetcode 488. Zuma Game

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.

 

Example 1:

Input: board = "WRRBBW", hand = "RB"
Output: -1
Explanation: WRRBBW -> WRR[R]BBW -> WBBW -> WBB[B]W -> WW

Example 2:

Input: board = "WWRRBBWW", hand = "WRBRW"
Output: 2
Explanation: WWRRBBWW -> WWRR[R]BBWW -> WWBBWW -> WWBB[B]WW -> WWWW -> empty

Example 3:

Input: board = "G", hand = "GGGGG"
Output: 2
Explanation: G -> G[G] -> GG[G] -> empty 

Example 4:

Input: board = "RBYYBBRRB", hand = "YRBGB"
Output: 3
Explanation: RBYYBBRRB -> RBYY[Y]BBRRB -> RBBBRRB -> RRRB -> B -> B[B] -> BB[B] -> empty 

 

Constraints:

  • You may assume that the initial row of balls on the table won’t have any 3 or more consecutive balls with the same color.
  • The number of balls on the table won't exceed 16, and the string represents these balls is called "board" in the input.
  • The number of balls in your hand won't exceed 5, and the string represents these balls is called "hand" in the input.
  • Both input strings will be non-empty and only contain characters 'R','Y','B','G','W'.

Accepted

12,565

Submissions

31,181

-------------------------------------------------------------------------------------------------------------------

这题猛地看上去是动态规划,但是不知道怎么写递推表达式。然后搜索,不知道怎么DFS下去。参考了别的人想法,每次算出某一个连续小段要多少,然后拼接字符串递归下去。。。

from collections import Counter


class Solution:
    def dfs(self, board, inhands, upper):
        i, l = 0, len(board)
        res = upper
        if (l == 0): #bug2: miss the return condition
            return 0

        while (i < l):
            j = i + 1
            while (j < l and board[j] == board[j - 1]):
                j += 1
            need = max(3 - (j - i), 0)
            if (inhands[board[i]] >= need):
                inhands[board[i]] -= need
                sub = self.dfs(board[:i] + board[j:], inhands, upper)
                res = min(res, need + sub)
                inhands[board[i]] += need
            i = j  # bug1 miss
        return res

    def findMinStep(self, board, hand):
        upper = 16*2
        res = self.dfs(board, Counter(hand), upper)
        return -1 if res == upper else res #bug3

s = Solution()
print(s.findMinStep("WRRBBW","RB"))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值