Leetcode notes: Nim Game

Source: Internet
Author: User

I. Title Description

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.

Two. Topic analysis

The main idea of the topic is as follows:

You're playing this Nim game with your friends: there's a pile of stones on the table, and you can take 1 to 3 of them each time. The winner is the one who removes the last stone. Suppose you are the first round to start taking stones.

Now everyone in your game has a very smart mind and a great strategy. Write a function pair with a given number of stones to figure out whether you can win the game.

For example, if there are 4 stones in the heap, you will never win the game: Whether you remove 1, 2, or 3 stones, the last 1 stones will be taken away by your friends.

For more on Nim game explanation, refer to the encyclopedia: http://baike.baidu.com/link?url= Uxwv7mndl-jkdwl6qj06zsx9luvazbck4xqdo6iecngh2lnagwomn7fyin_yrjphyaaygecf6yz2swc-irb2x_

In fact, for this single problem, you can use one line of code to solve. For example, if and only if there is a multiple of 4, the initiator will lose, the rest of the case can win.

Three. Sample code

class Solution{public:    boolcanWinNim(int n) {        return40;    }}

Four. Summary

The problem can be said to be no difficulty, but it can be changed to become a complex problem.

Leetcode notes: Nim Game

Related Article

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.