3360.移除石头游戏:while一下(不算了)

【LetMeFly】3360.移除石头游戏:while一下(不算了)

力扣题目链接:https://leetcode.cn/problems/stone-removal-game/

Alice 和 Bob 在玩一个游戏,他们俩轮流从一堆石头中移除石头,Alice 先进行操作。

  • Alice 在第一次操作中移除 恰好 10 个石头。
  • 接下来的每次操作中,每位玩家移除的石头数 恰好 为另一位玩家上一次操作的石头数减 1 。

第一位没法进行操作的玩家输掉这个游戏。

给你一个正整数 n 表示一开始石头的数目,如果 Alice 赢下这个游戏,请你返回 true ,否则返回 false 。

 

示例 1:

输入:n = 12

输出:true

解释:

  • Alice 第一次操作中移除 10 个石头,剩下 2 个石头给 Bob 。
  • Bob 无法移除 9 个石头,所以 Alice 赢下游戏。

示例 2:

输入:n = 1

输出:false

解释:

  • Alice 无法移除 10 个石头,所以 Alice 输掉游戏。

 

提示:

  • 1 <= n <= 50

解题方法:模拟

默认状态($state$)是Alice输(如果Alice不做点什么的话会输),她需要($need$)移除10个石头,移除完:

  • 输赢状态暂时改变
  • 石头总数减少
  • 下次需要移除的石头数量减少1

当石头总数不足一次移除时,输赢状态已成定局,返回之。

  • 时间复杂度$O(1)$,$10+9+8+7+6+5+4+3+2+1=52$,所以最多循环$7$次
  • 空间复杂度$O(1)$

当然也可以直接$O(1)$算出总共能移除几轮,但是这个数据量说实话不是很有必要。

AC代码

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/*
* @LastEditTime: 2026-11-26 07:55:55
*/
class Solution {
public:
bool canAliceWin(int n) {
bool state = false;
int need = 10;
while (true) {
if (n < need) {
return state;
}
n -= need--;
state = !state;
}
}
};

Python

1
2
3
4
5
6
7
8
9
10
11
'''
LastEditTime: 2026-11-26 08:04:25
'''
class Solution:
def canAliceWin(self, n: int) -> bool:
state, need = False, 10
while n >= need:
n -= need
need -= 1
state = not state
return state

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/*
* @LastEditTime: 2026-11-26 08:03:30
*/
class Solution {
public boolean canAliceWin(int n) {
boolean state = false;
int need = 10;
while (n >= need) {
n -= need--;
state = !state;
}
return state;
}
}

Go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/*
* @LastEditTime: 2026-11-26 08:01:55
*/
package main

func canAliceWin(n int) (state bool) {
need := 10
for n >= need {
n -= need
need--
state = !state
}
return
}

Rust

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/*
* @LastEditTime: 2026-11-26 08:05:26
*/
impl Solution {
pub fn can_alice_win(mut n: i32) -> bool {
let mut state = false;
let mut need = 10;
while n >= need {
n -= need;
need -= 1;
state = !state;
}
state
}
}

End

同步发文于CSDN和我的个人博客,原创不易,转载经作者同意后请附上原文链接哦~

千篇源码题解已开源


3360.移除石头游戏:while一下(不算了)
https://blog.letmefly.xyz/2026/11/26/LeetCode 3360.移除石头游戏/
作者
发布于
2026年11月26日
许可协议