Skip to content
This repository was archived by the owner on Sep 20, 2023. It is now read-only.

Commit 814128a

Browse files
aQuaaQua
aQua
authored and
aQua
committed
292 Time Limit Exceeded
1 parent e27ae9e commit 814128a

File tree

3 files changed

+62
-0
lines changed

3 files changed

+62
-0
lines changed

Algorithms/0292.nim-game/README.md

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# [292. Nim Game](https://leetcode.com/problems/nim-game/)
2+
3+
## 题目
4+
5+
You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones.
6+
7+
Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap.
8+
9+
For example, if there are 4 stones in the heap, then you will never win the game: no matter 1, 2, or 3 stones you remove, the last stone will always be removed by your friend.
10+
11+
Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
12+
13+
## 解题思路
14+
15+
见程序注释

Algorithms/0292.nim-game/nim-game.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
package Problem0292
2+
3+
func canWinNim(n int) bool {
4+
if n <= 3 {
5+
return true
6+
}
7+
8+
return !canWinNim(n-1) || !canWinNim(n-2) || !canWinNim(n-3)
9+
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package Problem0292
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
7+
"github.com/stretchr/testify/assert"
8+
)
9+
10+
// tcs is testcase slice
11+
var tcs = []struct {
12+
n int
13+
ans bool
14+
}{
15+
16+
{4, false},
17+
{5, true},
18+
{41, true},
19+
20+
// 可以有多个 testcase
21+
}
22+
23+
func Test_canWinNim(t *testing.T) {
24+
ast := assert.New(t)
25+
26+
for _, tc := range tcs {
27+
fmt.Printf("~~%v~~\n", tc)
28+
ast.Equal(tc.ans, canWinNim(tc.n), "输入:%v", tc)
29+
}
30+
}
31+
32+
func Benchmark_canWinNim(b *testing.B) {
33+
for i := 0; i < b.N; i++ {
34+
for _, tc := range tcs {
35+
canWinNim(tc.n)
36+
}
37+
}
38+
}

0 commit comments

Comments
 (0)