"Algorithmic skills" Leetcode 292 Nim Game

Source: Internet
Author: User

You were playing the following Nim Game with your friend:there was a heap of stones on the table and each time one of your take Turns to remove 1 to 3 stones. The one who removes, the last stone would be the winner. You'll take the first turn to remove the stones.

Both of you is very clever and has optimal strategies for the game. Write a function to determine whether your can win the game given the number of stones in the heap.

For example, if there is 4 stones in the heap and then you'll never win the Game:no matter 1, 2, or 3 stones you remove, The last stone is always being removed by your friend.

Topic:

You and your good friends are playing a game called Nim: there are a bunch of pebbles on the table, and you or your friends take turns from 1 to 3 pebbles. The man who can take the last remaining pebbles wins. You start to take.

Suppose: You and your friends are very high-IQ people, and all of them are veteran of the game (familiar with playing this game).

Can you write a function that calculates a given number of pebbles and whether you can win the game.

Eg: if you have 4 pebbles, you will lose, because whether you take one, 2 or 3, the last remaining pebbles will be finished by your friends.

Analysis: If it's your turn to take, there are 4 pebbles left, and you're in for a tragedy.

Similarly, if you have 8 pebbles left when you take them, whether you choose to take 1, 2 or 3, your friends will be able to make you the next time you take the remaining 4.

Recursion: Suppose in your turn when you take the time left 4*n a small stone, whether you choose to take 1, 2 or 3, your friends can let you take the next time you still have a n-1;

That is, your friend can let you take each time before you have left 4n pebbles; (n is a positive integer greater than or equal to 1); So push it down and you lose.

1  Public class Solution {2      Public boolean canwinnim (int  n) {3         return n% 4 = = 0; 4     }5 }

"Algorithmic skills" Leetcode 292 Nim Game

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.