博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
294. Flip Game II
阅读量:5931 次
发布时间:2019-06-19

本文共 2020 字,大约阅读时间需要 6 分钟。

题目:

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 twoconsecutive "++" 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.

链接:  

题解:

求是否startng player可以有一种策略保证赢取游戏。直觉就是dfs +backtracking。 代码和Flip Game I基本一样,不过加入了验证下一步的一个条件语句。假如下一步next,对手不能赢,则这一步我们可以赢。看了Discuss以后发现还可以有O(n2)的DP做法,有些Game Theory的成分。Stellari大神好厉害。

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;    }}

Reference:

https://leetcode.com/discuss/64344/theory-matters-from-backtracking-128ms-to-dp-0ms

https://leetcode.com/discuss/64291/share-my-java-backtracking-solution

https://leetcode.com/discuss/64522/simple-backtracking-inspired-by-flip-game-i

https://leetcode.com/discuss/64357/memoization-3150ms-130ms-44ms-python

https://leetcode.com/discuss/64486/backtracking-solution-time-optimization-through-205ms-19ms

https://leetcode.com/discuss/64350/short-java-%26-ruby

https://leetcode.com/discuss/64293/1-line-python-solution

https://leetcode.com/discuss/64332/java-recursive-backtracking-solution-27ms

https://leetcode.com/discuss/64302/easy-to-understand-java-solution

http://lucida.me/blog/developer-reading-list/

转载地址:http://jbutx.baihongyu.com/

你可能感兴趣的文章
一站式解决,Android 拍照 图库的各种问题
查看>>
lsof命令
查看>>
阿里云云计算ACP考试知识点(标红为重点)
查看>>
从零开始来看一下Java泛型的设计
查看>>
Shell编程基础
查看>>
Shell之Sed常用用法
查看>>
3.1
查看>>
校验表单如何摆脱 if else ?
查看>>
跨运营商组播传送案例(multicast-proxy-register应用)
查看>>
JTable的DefaultModel方法getValueAt(a,row)
查看>>
Good Bye 2013 A
查看>>
Automatic Sql Server Backup Utility Using sqlserveragent
查看>>
Java是如何读取和写入浏览器Cookies的
查看>>
篇一、安装配置Android Studio
查看>>
C#代码安装、卸载、监控Windows服务
查看>>
2014年抢票总结
查看>>
zephir开发的扩展“wudimei框架”之模板词法扫描(三)完成代码切分
查看>>
ML 线性回归Linear Regression
查看>>
【转载】SweetAlert2 使用
查看>>
oracle如何用sql查看触发器?
查看>>