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. 七. SpringCloud服务配置

    1. SpringCloud Config概述 1.1 分布式系统面临的配置问题 微服务意味着要将单体应用中的业务拆分成一个一个子服务,每个服务的粒度相对较小,因此系统中会出现大量的服务.由于每个服务 ...

  2. 鸿蒙的js开发模式19:鸿蒙手机下载python服务器端文件的实现

    目录:1.承接上篇鸿蒙客户端上传文件2.域名通过内网穿透工具3.python服务器端代码4.鸿蒙手机的界面和业务逻辑5.<鸿蒙的js开发模式>系列文章合集 1.承接上篇鸿蒙客户端上传文件, ...

  3. Web微信协议

    [文档]Web微信协议 1.登录 1.1 获取uuid(get) 请求 https://login.wx.qq.com/jslogin?appid=wx782c26e4c19acffb&red ...

  4. 24端口以太网FPGA的开发板

    板卡架构 板载FPGA(K7-325T)处理24端口10/100/1000M以太网数据: FPGA外挂4Gbit的DDR3颗粒,最大支持800MHz: 板载CPU进行系统配置.管理,并与客户端软件通信 ...

  5. 超详细Linux新手快速入门(一)——Linux的介绍安装以及虚拟机的介绍安装

    一.Linux的介绍 1.Linux和Windows的比较  Linux是一款操作系统,其性能稳定,因其防火墙组件高效安全.简单易配置,所以获得了追求速度和安全的一些企业和人群的青睐.与我们日常所熟知 ...

  6. 【odoo14】第五章、服务器侧开发-基础

    本章包含如下内容: 定义模型方法和使用api装饰器 向用户反馈错误信息 针对不同的对象获取空数据集 创建新纪录 更新数据集数据 搜索数据 组合数据集 过滤数据集 遍历记录集 排序数据集 重写已有业务逻 ...

  7. Linux 用户登陆提示This account is currently not available

    使用 su 切换到用户 hdfs 时提示:This account is currently not available,使用 hdfs 用户登陆会直接退出 ssh 窗口. 此时可以尝试检查文件 /e ...

  8. CobaltStrike 和 Metasploit 联动

    出品|MS08067实验室(www.ms08067.com) 本文作者:掉到鱼缸里的猫(Ms08067内网安全小组成员) 个人觉得CobaltStrike图形化的界面和丰富的功能,是一个超强的后渗透框 ...

  9. c++反汇编 switch

    switch 线性处理 24: int nIndex = 0; 01377EBE C7 45 F8 00 00 00 00 mov dword ptr [nIndex],0 25: scanf(&qu ...

  10. 复制粘贴Ctrl+C改为自定义单键

    目录 那一瞬间不想用Ctrl+C了 (一)搜索渠道 关键词搜索 (二)方案对比 (三)最终方案Ditto 使用方法 (四)案例 1. 替换Ctrl+C快捷键: 2. 将英文小写替换为大写: 那一瞬间不 ...