Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 5104e8c

Browse files
committed
"Nim Game"
1 parent a7092d3 commit 5104e8c

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

‎README.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@ The `☢` means that you need to have a LeetCode Premium Subscription.
2525

2626
| | Problem | Solution |
2727
| --- | ------------------------------------------------------------ | ------------------ |
28+
| 292 | [Nim Game] | [C](src/292.c) |
29+
| 291 | [Word Pattern II]| |
2830
| 290 | [Word Pattern] | [C++](src/290.cpp) |
2931
| 289 | [Game of Life] | [C](src/289.c) |
3032
| 288 | [Unique Word Abbreviation]| |
@@ -303,6 +305,8 @@ The `☢` means that you need to have a LeetCode Premium Subscription.
303305
[LeetCode algorithm problems]: https://leetcode.com/problemset/algorithms/
304306

305307

308+
[Nim Game]: https://leetcode.com/problems/nim-game/
309+
[Word Pattern II]: https://leetcode.com/problems/word-pattern-ii/
306310
[Word Pattern]: https://leetcode.com/problems/word-pattern/
307311
[Game of Life]: https://leetcode.com/problems/game-of-life/
308312
[Unique Word Abbreviation]: https://leetcode.com/problems/unique-word-abbreviation/

‎src/292.c‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
#include <stdbool.h>
4+
#include <assert.h>
5+
6+
/* Both two methods below suck, way too slow.
7+
8+
bool canWinNim(int n) {
9+
if (n <= 0) return false;
10+
if (n >= 1 && n <= 3) return true;
11+
12+
return !canWinNim(n - 1) | !canWinNim(n - 2) | !canWinNim(n - 3);
13+
}
14+
15+
bool canWinNim(int n) {
16+
if (n <= 0) return false;
17+
if (n >= 1 && n <= 3) return true;
18+
19+
int *dp = (int *)malloc((n + 1) * sizeof(int));
20+
21+
dp[0] = false;
22+
dp[1] = dp[2] = dp[3] = true;
23+
24+
int i;
25+
for (i = 4; i <= n; i++) {
26+
dp[i] = !dp[i - 1] | !dp[i - 2] | !dp[i - 3];
27+
}
28+
29+
bool ans = dp[n];
30+
free(dp);
31+
32+
return ans;
33+
}
34+
*/
35+
36+
bool canWinNim(int n) {
37+
return n % 4;
38+
}
39+
40+
int main() {
41+
assert(canWinNim(1) == true);
42+
assert(canWinNim(4) == false);
43+
assert(canWinNim(5) == true);
44+
assert(canWinNim(7) == true);
45+
assert(canWinNim(34) == true);
46+
assert(canWinNim(1348820612) == false);
47+
48+
printf("all tests passed!\n");
49+
50+
return 0;
51+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /