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的更多相关文章

  1. 294. 翻转游戏 II

    题目: 链接:https://leetcode-cn.com/problems/flip-game-ii/ 你和朋友玩一个叫做「翻转游戏」的游戏,游戏规则:给定一个只有 + 和 - 的字符串.你和朋友 ...

  2. Leetcode力扣45题 跳跃游戏 II

    原题目: 跳跃游戏 II 给定一个非负整数数组,你最初位于数组的第一个位置. 数组中的每个元素代表你在该位置可以跳跃的最大长度. 你的目标是使用最少的跳跃次数到达数组的最后一个位置. 示例: 输入: ...

  3. lintcode 中等题: reverse linked list II 翻转链表II

    题目 翻转链表 II 翻转链表中第m个节点到第n个节点的部分 样例 给出链表1->2->3->4->5->null, m = 2 和n = 4,返回1->4-> ...

  4. LeetCode 294. Flip Game II

    原题链接在这里:https://leetcode.com/problems/flip-game-ii/ 题目: You are playing the following Flip Game with ...

  5. [LeetCode] 45. Jump Game II 跳跃游戏 II

    Given an array of non-negative integers, you are initially positioned at the first index of the arra ...

  6. 【LeetCode每天一题】Jump Game II(跳跃游戏II)

    Given an array of non-negative integers, you are initially positioned at the first index of the arra ...

  7. LeetCode(45): 跳跃游戏 II

    Hard! 题目描述: 给定一个非负整数数组,你最初位于数组的第一个位置. 数组中的每个元素代表你在该位置可以跳跃的最大长度. 你的目标是使用最少的跳跃次数到达数组的最后一个位置. 示例: 输入: [ ...

  8. [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 ...

  9. 045 Jump Game II 跳跃游戏 II

    给定一个非负整数数组,你最初位于数组的首位.数组中的每个元素表示你在该位置的最大跳跃长度.你的目标是用最小跳跃次数到达最后一个索引.例如: 给定一个数组 A = [2,3,1,1,4]跳到最后一个索引 ...

随机推荐

  1. 数组,字符串,json互相转换

    数组转字符串 var arr = [1,2,3,4,'巴德','merge']; var str = arr.join(','); console.log(str); // 1,2,3,4,巴德,me ...

  2. AD-logon workstation

    默认AD登录到限制为64个 原因 发生此问题的原因是User-Workstations属性的Range-Upper值为1,024个字符.使用Active Directory用户和计算机输入NetBIO ...

  3. MP4文件批量转码成MP3

    需求背景:最近为了学python爬虫,在论坛里找了不少视频教程,非常棒.但有时看视频不方便,就想着能否把视频批量转码成音频,这样在乘坐地铁公交的时候也能学习了. 解决路径:有了需求,我首先在论坛里搜了 ...

  4. keras神经网络开发知识笔记

    mnist数据集获取60000个训练样本和10000个测试样本,样本为0-9十个数字,用全连接神经网络进行训练,并测试结果. 例程采用60000个数据样本进行训练,对于一般的电脑来说,这样训练会比较费 ...

  5. Pycharm中打开Terminal方式

    点击剪头的图标就可以在左侧出现Terminal

  6. Classification and Decision Trees

    分类和决策树(DT). 决策树是预测建模机器学习的一种重要算法. 决策树模型的表示是二叉树.就是算法和数据结构中的二叉树,没什么特别的.每个节点表示一个单独的输入变量(x)和该变量上的左右孩子(假设变 ...

  7. H5中实现加载更多的逻辑及代码执行。

    H5中加载更多的逻辑总结: 1.首先,需要三个底部的提示,分别是“加载中”.“--我是有底线的--”.“暂时没有记录”,当然,这三句话根据不同的项目,可以自定义.具体代码例子如下: <div c ...

  8. 在WinDbg里使用MEX调试扩展

    简介 针对WinDbg的MEX调试扩展可以帮助您简化常见的调试器任务,并为调试器提供强大的文本筛选功能.此扩展被Microsoft支持工程师广泛用于解决流程应用程序的故障. 下载&安装 下载m ...

  9. pgloader 学习(三)快速使用

    pgloader 支持多种数据源数据的加载,以下列出简单的操作命令,后边会有详细的使用说明 csv 格式内容加载 预备说明 需要先在pg 数据库创建表 create table districts_l ...

  10. 55、Spark Streaming:updateStateByKey以及基于缓存的实时wordcount程序

    一.updateStateByKey 1.概述 SparkStreaming 7*24 小时不间断的运行,有时需要管理一些状态,比如wordCount,每个batch的数据不是独立的而是需要累加的,这 ...