Leetcode 博弈论先手必胜解题思路(Leetcode 292877)

it2025-10-27  5

 就一个一个的枚举,1-3块手头,先手必胜,4块手头,先手必负,

5个石头,拿一个,让对手变成4个,那么必胜。

8个石头,不管怎么拿,必负。

因此可归纳出4的倍数的石头时,都必输。

这种是最简单的博弈论问题,因为容易枚举,很容易找到规律。

 

这种存在一个递归枚举的做法,非常经典,但是会超时。

class Solution { public: bool stoneGame(vector<int>& piles) { return helper(0,piles.size()-1,0,0,true,piles); } bool helper(int left, int right, int scoreA, int scoreB, bool turnA, vector<int>& piles){ if(left==right){ return scoreA>scoreB; } if(turnA){ if(helper(left+1,right,scoreA+piles[left],scoreB,!turnA,piles)||helper(left,right-1,scoreA+piles[right],scoreB,!turnA,piles)) return true; }else{ if(helper(left+1,right,scoreA,scoreB+piles[left],!turnA,piles)&&helper(left,right-1,scoreA,scoreB+piles[right],!turnA,piles)) return true; } return false; } };

 

 

 

 

 

最新回复(0)