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.

Examples:

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

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

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

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

Note:

  1. 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.
  2. The number of balls on the table won't exceed 20, and the string represents these balls is called "board" in the input.
  3. The number of balls in your hand won't exceed 5, and the string represents these balls is called "hand" in the input.
  4. Both input strings will be non-empty and only contain characters 'R','Y','B','G','W'.

Approach #1: DFS. [My Code][Wrong].

class Solution {
int ret = Integer.MAX_VALUE; public int findMinStep(String board, String hand) { dfs(board, hand, 0); return ret == Integer.MAX_VALUE ? -1 : ret;
} public void dfs(String board, String hand, int cur) {
if (dontHave(hand) && board.length() != 0) return;
if (board == null && board.length() == 0)
ret = Math.min(ret, cur); if (board.length() < 2 && inHand(hand, board.charAt(0))) {
board += board.charAt(0);
dfs(board, hand, cur+1);
} for (int i = 1; i < board.length(); ++i) {
StringBuilder copy = new StringBuilder(board);
boolean isChange = false; if (board.charAt(i) == board.charAt(i-1) && inHand(hand, board.charAt(i))) {
copy.deleteCharAt(i-1);
copy.deleteCharAt(i-1);
String temp = trim(copy);
dfs(temp, hand, cur+1);
isChange = true;
} // recover
if (isChange) {
hand += board.charAt(i);
}
}
} public String trim(StringBuilder temp) {
if (temp == null || temp.length() == 0) return "";
int count = 1;
for (int i = 1; i < temp.length(); ++i) {
if (temp.charAt(i-1) == temp.charAt(i)) {
count++;
} else {
if (count >= 3) {
int lastPos = i - count;
return trim(temp.delete(lastPos, i));
}
count = 1;
}
}
return temp.toString();
} public boolean inHand(String hand, Character c) {
for (int i = 0; i < hand.length(); ++i) {
if (hand.charAt(i) == c) {
hand.charAt(i) = '#';
return true;
}
}
return false;
} public boolean dontHave(String hand) {
for (int i = 0; i < hand.length(); ++i) {
if (hand.charAt(i) != '#') return false;
}
return true;
}
}

  

Approach #2: DFS. [Java]

class Solution {
int MaxNum = 6; public int findMinStep(String board, String hand) {
int ret = MaxNum;
int[] handCount = new int[26];
for (int i = 0; i < hand.length(); ++i)
handCount[hand.charAt(i) - 'A']++; ret = dfs(board+"#", handCount); return ret == MaxNum ? -1 : ret;
} public int dfs(String s, int[] h) {
s = removeConsecutives(s);
if (s.equals("#")) return 0;
int rs = MaxNum, need = 0;
for (int i = 0, j = 0; j < s.length(); ++j) {
if (s.charAt(i) == s.charAt(j)) continue;
need = 3 - (j - i);
if (h[s.charAt(i)-'A'] >= need) {
h[s.charAt(i)-'A'] -= need;
rs = Math.min(rs, need + dfs(s.substring(0, i) + s.substring(j), h));
h[s.charAt(i)-'A'] += need;
}
i = j;
}
return rs;
} public String removeConsecutives(String s) {
for (int i = 0, j = 0; j < s.length(); ++j) {
if (s.charAt(i) == s.charAt(j)) continue;
if (j - i >= 3) {
return removeConsecutives(s.substring(0, i) + s.substring(j));
} else i = j;
}
return s;
} }

  

Reference:

https://leetcode.com/problems/zuma-game/discuss/97010/%22short%22-java-solution-beats-98

488. Zuma Game的更多相关文章

  1. 488 Zuma Game 祖玛游戏

    回忆一下祖玛游戏.现在桌上有一串球,颜色有红色(R),黄色(Y),蓝色(B),绿色(G),还有白色(W). 现在你手里也有几个球.每一次,你可以从手里的球选一个,然后把这个球插入到一串球中的某个位置上 ...

  2. LeetCode All in One题解汇总(持续更新中...)

    突然很想刷刷题,LeetCode是一个不错的选择,忽略了输入输出,更好的突出了算法,省去了不少时间. dalao们发现了任何错误,或是代码无法通过,或是有更好的解法,或是有任何疑问和建议的话,可以在对 ...

  3. All LeetCode Questions List 题目汇总

    All LeetCode Questions List(Part of Answers, still updating) 题目汇总及部分答案(持续更新中) Leetcode problems clas ...

  4. leetcode 学习心得 (2) (301~516)

    源代码地址:https://github.com/hopebo/hopelee 语言:C++ 301. Remove Invalid Parentheses Remove the minimum nu ...

  5. leetcode hard

    # Title Solution Acceptance Difficulty Frequency     4 Median of Two Sorted Arrays       27.2% Hard ...

  6. LeetCode All in One 题目讲解汇总(转...)

    终于将LeetCode的免费题刷完了,真是漫长的第一遍啊,估计很多题都忘的差不多了,这次开个题目汇总贴,并附上每道题目的解题连接,方便之后查阅吧~ 如果各位看官们,大神们发现了任何错误,或是代码无法通 ...

  7. bzoj1032 [JSOI2007]祖码Zuma

    1032: [JSOI2007]祖码Zuma Time Limit: 10 Sec  Memory Limit: 162 MBSubmit: 672  Solved: 335[Submit][Stat ...

  8. Codeforces Round #336 Zuma

    D. Zuma time limit per test:  2 seconds memory limit per test:  512 megabytes input:  standard input ...

  9. Codeforces Round #336 (Div. 2) D. Zuma 区间dp

    D. Zuma   Genos recently installed the game Zuma on his phone. In Zuma there exists a line of n gems ...

随机推荐

  1. 后端程序员之路 45、nginx CORS 跨域

    在提供api给其它应用使用时,有时我们会要限制它的跨域使用,而有时,我们又要用CORS来打破AJAX只能同源使用的限制 跨域资源共享 CORS 详解 - 阮一峰的网络日志http://www.ruan ...

  2. MySQL提权 通过UDF

    目录 UDF是什么 命令执行 文本写入 Example: 远程写入 反弹Shell 提权 UDF是什么 参考:https://www.cnblogs.com/litlife/p/9030673.htm ...

  3. 【转载】几张图轻松理解String.intern()

    出处:https://blog.csdn.net/soonfly/article/details/70147205 在翻<深入理解Java虚拟机>的书时,又看到了2-7的 String.i ...

  4. PBR:基于物理的渲染(Physically Based Rendering)+理论相关

    一: 关于能量守恒 出射光线的能量永远不能超过入射光线的能量(发光面除外).如图示我们可以看到,随着粗糙度的上升镜面反射区域的会增加,但是镜面反射的亮度却会下降.如果不管反射轮廓的大小而让每个像素的镜 ...

  5. python工业互联网应用实战7—业务层

    本章我们演示代码是如何"进化"的,实战的企业日常开发过程中,系统功能总伴随着业务的不断增加,早期简单的代码慢慢的越来越复杂,敏捷编程中的"禅"--简单设计.快速 ...

  6. WebRTC 音视频同步原理与实现

    所有的基于网络传输的音视频采集播放系统都会存在音视频同步的问题,作为现代互联网实时音视频通信系统的代表,WebRTC 也不例外.本文将对音视频同步的原理以及 WebRTC 的实现做深入分析. 时间戳 ...

  7. 微服务架构Day16-SpringBoot之监控管理

    监控管理使用步骤 通过引入spring-boot-starter-actuator,可以使用SpringBoot提供应用监控和管理的功能.可以通过HTTP,JMX,SSH协议来进行操作,自动得到审计, ...

  8. python爬去壁纸网站上的所有壁纸

    import requests as r 2 from bs4 import BeautifulSoup 3 import os 4 base_url = "http://www.win40 ...

  9. spring-boot记录sql探索

    目标记录每次请求内的http.es.mysql耗时,本篇讨论mysql部分 为什么说要探索,这不是很简单的事么?但是能满足以下几点么? 能记录limit等参数 能将参数和sql写一起,能直接使用 能记 ...

  10. 【关系抽取-R-BERT】定义训练和验证循环

    [关系抽取-R-BERT]加载数据集 [关系抽取-R-BERT]模型结构 [关系抽取-R-BERT]定义训练和验证循环 相关代码 import logging import os import num ...