Tuesday, March 23, 2021

LeetCode [488]

 488. Zuma Game

Hard

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.
  • 1 <= board.length <= 16
  • 1 <= hand.length <= 5
  • Both input strings will be non-empty and only contain characters 'R','Y','B','G','W'.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class Solution {
    int minOp = Integer.MAX_VALUE;
    Set<String> set = new HashSet<>();
    public int findMinStep(String board, String hand) {
        helper(board, hand, 0);
        return minOp == Integer.MAX_VALUE ? -1 : minOp;
    }

    void helper(String b, String h, int op) {
        set.add(new String(b+" "+h));
        if (op >= minOp) return;
        if (b.length() == 0) {
            minOp = Math.min(op, minOp);
            return;
        }

        for (int i = 0; i <= b.length(); ++i) {
            for (int j = 0; j < h.length(); ++j) {
                String b1 = b.substring(0, i) + h.substring(j, j + 1) + b.substring(i);
                String h1 = h.substring(0, j) + h.substring(j + 1);
                boolean cont = true;
                while (cont) {
                    cont = false;
                    int l = 0, r = 0;
                    while (l < b1.length()) {
                        r = l;
                        while (r < b1.length() && b1.charAt(l) == b1.charAt(r)) r++;
                        if (r - l >= 3) {
                            b1 = b1.substring(0, l) + b1.substring(r);
                            cont = true;
                        }
                        l = r;
                    }
                }
                String key = b1+" "+h1;
                if(!set.contains(key)) helper(b1, h1, op + 1);
            }
        }

    }
}

No comments:

Post a Comment