zoukankan      html  css  js  c++  java
  • [Locked] Flip Game I & II

    Flip Game I

    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 compute all possible states of the string after one valid move.

    For example, given s = "++++", after one move, it may become one of the following states:

    [
      "--++",
      "+--+",
      "++--"
    ]
    

    If there is no valid move, return an empty list [].

    分析:

      一层处理即可

    代码:

    vector<string> flipGame(string str) {
        vector<string> vs;
        for(int i = 0; i < str.length() - 1; i++) {
            if(str[i] == '+' && str[i + 1] == '+') {
                str[i] = str[i + 1] = '-';
                vs.push_back(str);
                str[i] = str[i + 1] = '+';
            }
        }
        return vs;
    }

    Flip Game 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.

    分析:

      第一想法是找到合适的规律,可以直接从当前状态判断是否必胜,经过尝试,难以直接判断;所以采用一般解法,当两边都是没有失误的高手状态下,有以下规律:

        1、终结点是必败点(P点);

        2、从任何必胜点(N点)操作,至少有一种方法可以进入必败点(P点)

        3、无论如何操作, 从必败点(P点)都只能进入必胜点(N点).

      这里用到的就是1,2,3规律,对手无点可操作,则以失败终结;自己必胜,则至少一种方法进入下一轮必败点;若不能必胜,则找不到方法进入下一轮必败点;若自己必败,则无论用什么方法下一轮都是必胜点。

    代码:

    bool canwin(string str) {
        for(int i = 0; i < str.length() - 1; i++) {
            if(str[i] == '+' && str[i + 1] == '+') {
                str[i] = str[i + 1] = '-';
                int win = !canwin(str);
                str[i] = str[i + 1] = '+';
                if(win)
                    return true;
            }
        }
        return false;
    }
  • 相关阅读:
    POJ 1979 Red and Black
    MyEclipse7.0破解下载
    【android开发】Android防止内存溢出浅析
    数据库索引的作用和长处缺点
    怎样基于android4.4.2的源代码和android-4.3.1_r1的驱动编译I9250的ROM
    Eclipse中SVN的安装步骤(两种)和用法
    又拍云服务评測分享
    Objective-C语法之代码块(block)的使用
    《linux 内核全然剖析》 chapter 2 微型计算机组成结构
    浅谈UML的概念和模型之UML九种图
  • 原文地址:https://www.cnblogs.com/littletail/p/5199634.html
Copyright © 2011-2022 走看看