[LeetCode] 294. Flip Game II 翻转游戏 II
You are playing the following Flip Game with your friend: Given a string that contains only these two characters: +
and -
, you and your friend take turns to flip two consecutive "++"
into "--"
. The game ends when a person can no longer make a move and therefore the other person will be the winner.
Write a function to determine if the starting player can guarantee a win.
For example, given s = "++++"
, return true. The starting player can guarantee a win by flipping the middle "++"
to become "+--+"
.
Follow up:
Derive your algorithm's runtime complexity.
293. Flip Game 的拓展,这次求是否先玩者可以有一种策略一定赢游戏。
解法: backtracking
Java:
public class Solution {
public boolean canWin(String s) {
for ( int i = 0; i < s.length() - 1; i ++ ){
if ( s.charAt ( i ) == '+' && s.charAt( i + 1 ) == '+' ){
StringBuilder sb = new StringBuilder ( s );
sb.setCharAt ( i , '-');
sb.setCharAt ( i + 1 ,'-');
if ( !canWin ( sb.toString() ) )
return true;
}
}
return false;
}
}
Java: backtracking
public boolean canWin(String s) {
if(s==null||s.length()==0){
return false;
} return canWinHelper(s.toCharArray());
} public boolean canWinHelper(char[] arr){
for(int i=0; i<arr.length-1;i++){
if(arr[i]=='+'&&arr[i+1]=='+'){
arr[i]='-';
arr[i+1]='-'; boolean win = canWinHelper(arr); arr[i]='+';
arr[i+1]='+'; //if there is a flip which makes the other player lose, the first play wins
if(!win){
return true;
}
}
} return false;
}
Java: DP, Time Complexity - O(2n), Space Complexity - O(2n)
public class Solution {
public boolean canWin(String s) {
char[] arr = s.toCharArray();
for(int i = 1; i < s.length(); i++) {
if(arr[i] == '+' && arr[i - 1] == '+') {
arr[i] = '-';
arr[i - 1] = '-';
String next = String.valueOf(arr);
if(!canWin(next)) {
return true;
}
arr[i] = '+';
arr[i - 1] = '+';
}
} return false;
}
}
Python:
class Solution(object):
def canWin(self, s):
"""
:type s: str
:rtype: bool
"""
for i in range(len(s) - 1): # 寻找所有的翻转可能
if s[i:i+2] == "++":
current = s[0:i] + "--" + s[i+2:] # 把找到的++变成-- if not self.canWin(current): # 看当前的字串是否存在边界,没有++了
return True # 对手不能赢,那就是当前翻转的赢了
return False # loop中没有返回,不能赢,当前翻转的输了
C++:
class Solution {
public:
bool canWin(string s) {
for (int i = 1; i < s.size(); ++i) {
if (s[i] == '+' && s[i - 1] == '+' && !canWin(s.substr(0, i - 1) + "--" + s.substr(i + 1))) {
return true;
}
}
return false;
}
};
C++:
class Solution {
public:
bool canWin(string s) { //朴素回溯,715MS
int len=s.size();
if(len<=1) return false;
for(int i=0;i<len-1;i++) {
string tmp=s;
if(s[i]=='+'&&s[i+1]=='+') {
tmp[i]='-';tmp[i+1]='-';
bool f=canWin(tmp);
if(!f) return true;
}
}
return false;
}
};
C++:
class Solution {
public:
bool canWin(string s) { //记录中间结果,39MS
int len=s.size();
if(len<=1) return false;
if(Memory_Map.find(s)!=Memory_Map.end()) {
return Memory_Map[s];
}
for(int i=0;i<len-1;i++) {
string tmp=s;
if(s[i]=='+'&&s[i+1]=='+') {
tmp[i]='-';tmp[i+1]='-';
bool f=canWin(tmp);
if(!f) {
Memory_Map[s]=true;
return true;
}
}
}
Memory_Map[s]=false;
return false;
}
private:
unordered_map<string,bool> Memory_Map;
};
类似题目:
[LeetCode] 293. Flip Game 翻转游戏
All LeetCode Questions List 题目汇总
[LeetCode] 294. Flip Game II 翻转游戏 II的更多相关文章
- 294. 翻转游戏 II
题目: 链接:https://leetcode-cn.com/problems/flip-game-ii/ 你和朋友玩一个叫做「翻转游戏」的游戏,游戏规则:给定一个只有 + 和 - 的字符串.你和朋友 ...
- Leetcode力扣45题 跳跃游戏 II
原题目: 跳跃游戏 II 给定一个非负整数数组,你最初位于数组的第一个位置. 数组中的每个元素代表你在该位置可以跳跃的最大长度. 你的目标是使用最少的跳跃次数到达数组的最后一个位置. 示例: 输入: ...
- lintcode 中等题: reverse linked list II 翻转链表II
题目 翻转链表 II 翻转链表中第m个节点到第n个节点的部分 样例 给出链表1->2->3->4->5->null, m = 2 和n = 4,返回1->4-> ...
- LeetCode 294. Flip Game II
原题链接在这里:https://leetcode.com/problems/flip-game-ii/ 题目: You are playing the following Flip Game with ...
- [LeetCode] 45. Jump Game II 跳跃游戏 II
Given an array of non-negative integers, you are initially positioned at the first index of the arra ...
- 【LeetCode每天一题】Jump Game II(跳跃游戏II)
Given an array of non-negative integers, you are initially positioned at the first index of the arra ...
- LeetCode(45): 跳跃游戏 II
Hard! 题目描述: 给定一个非负整数数组,你最初位于数组的第一个位置. 数组中的每个元素代表你在该位置可以跳跃的最大长度. 你的目标是使用最少的跳跃次数到达数组的最后一个位置. 示例: 输入: [ ...
- [LeetCode] Random Flip Matrix 随机翻转矩阵
You are given the number of rows n_rows and number of columns n_cols of a 2D binary matrix where all ...
- 045 Jump Game II 跳跃游戏 II
给定一个非负整数数组,你最初位于数组的首位.数组中的每个元素表示你在该位置的最大跳跃长度.你的目标是用最小跳跃次数到达最后一个索引.例如: 给定一个数组 A = [2,3,1,1,4]跳到最后一个索引 ...
随机推荐
- BZOJ2523/LOJ2646 聪明的学生
BZOJ2523/LOJ2646 聪明的学生 第一道CTSC的题. 因为是思维题,所以思路就不写了.直接看代码吧. #include<bits/stdc++.h> #define M 30 ...
- 基于springboot2.x集成缓存注解及设置过期时间
添加以下配置信息: /** * 基于注解添加缓存 */ @Configuration @EnableCaching public class CacheConfig extends CachingCo ...
- 快排算法Java版-每次以最左边的值为基准值手写QuickSort
如题 手写一份快排算法. 注意, 两边双向找值的时候, 先从最右边起找严格小于基准值的值,再从最左边查找严格大于基准base的值; 并且先右后左的顺序不能反!!这个bug改了好久,233~ https ...
- java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver
java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver at java.net.URLClassLoader.findClass(URLC ...
- How to Start Up an Open Source Company
https://evolveum.com/start-open-source-company/ Evolveum is a successful open source company now. We ...
- 实现redis缓存,缓存穿透简单原理
String get(String key) { String value = redis.get(key); if (value == null) { if (redis.setnx(key_mut ...
- nginx syslog 配置
以下是一个简单的实践,主要是打算测试nginx 与graylog 的集成,为了简单都是使用容器运行的,同时也测试了 nginx 对于配置多个access_log 的处理 环境准备 docker-com ...
- 移动端touch触摸事件(滑动效果和手势操作)
一.定义 ①touch是移动端的触摸事件,而且是一组事件,主要有以下事件: touchstart 事件:当手指触摸屏幕的时候触发 touchmove 事件:当手指在屏幕来回滑动的时候触发 touche ...
- B. Heaters ( Codeforces Round #515 (Div. 3) )
题解:对于每个点 i 来说,从 j = i + r - 1 开始往前找,如果找到一个 a [ j ] 是 1 ,那么就把它选上,但是我们需要判断交界处,也就是如果前面选的那个可以让这个点变温暖,就不用 ...
- shell 查看目前机器listen的所有端口
netstat -lnp 这条命令的意思是列出系统里面监听网络连接的端口号和相应的进程PID.参数说明:-t:表示列出TCP连接(也可以加上-u参数表示同时列出UDP网络连接)-l:表示列出正在网络监 ...