描述
有 n 个硬币排成一条线。两个参赛者轮流从右边依次拿走 1 或 2 个硬币,直到没有硬币为止。拿到最后一枚硬币的人获胜。
请判定 先手玩家 必胜还是必败?
题目链接:https://www.lintcode.com/problem/394/
方法一:递归
#include "iostream"
using namespace std;
bool s(int n);
bool f(int n){
//如果剩下1或者2个硬币,先手赢。
if(n == 1 || n == 2){
return true;
}
//先手可能拿一个或两个,如果后手拿完返回有一个是true,那么先手赢。
return s(n - 1) || s(n - 2);
}
bool s(int n){
//如果剩下1或者2个硬币,先手赢。
if(n == 1 || n == 2){
return false;
}
//后手可能拿一个或两个,如果先手拿完返回有一个是false,那么后手赢
return f(n - 1) && f(n - 2);
}
int main(){
int n;
cin >> n;
cout << f(n) << endl;
}
方法二:dp,时间复杂度(O(n))
class Solution {
public:
/**
* @param n: An integer
* @return: A boolean which equals to true if the first player will win
*/
bool firstWillWin(int n) {
// write your code here
if(n == 0){
return false;
}
int f[n + 1];
int s[n + 1];
f[1] = true;
f[2] = true;
s[1] = false;
s[2] = false;
for(int i = 3; i <= n; i++){
f[i] = s[i - 1] || s[i - 2];
s[i] = f[i - 1] && f[i - 2];
}
return f[n];
}
};
方法三:发现规律,时间复杂度(O(1))
class Solution {
public:
/**
* @param n: An integer
* @return: A boolean which equals to true if the first player will win
*/
bool firstWillWin(int n) {
// write your code here
return !(n % 3 == 0);
}
};