奇怪的核心转储使用无序映射

时间:2017-12-04 00:32:49

标签: c++ segmentation-fault unordered-map coredump

这是我的代码和我正在处理代码的问题,并想知道为什么我的案例中有核心转储?

问题,

你正和你的朋友一起玩下面的Nim游戏:桌子上有一堆石头,每次你轮流去除1到3块石头。移除最后一块石头的人将成为赢家。你将在第一个转弯处取出石头。

你们两个都很聪明,并且拥有最佳的游戏策略。编写一个函数来确定你是否可以在堆中的石头数量的情况下赢得游戏。

例如,如果堆中有4块石头,那么你永远不会赢得游戏:无论你移走1,2或3块石头,最后的石头都会被你的朋友移除。

代码,

#include <iostream>
class Solution {
public:
    bool canWinNim(int n) {
        std::unordered_map<int, bool> cache;
        return canWinNimHelper(n, cache);
    }

    bool canWinNimHelper(int n, std::unordered_map<int, bool>& cache) {
        if (n <= 3) {
            return true;   
        }
        auto iter = cache.find(n);
        if (iter != cache.end()) {
            return iter->second;
        }
        if ((!canWinNimHelper(n-1, cache)) || (!canWinNimHelper(n-2, cache)) || (!canWinNimHelper(n-3, cache))) {
            cache[n] = true;
            return true;
        }

        cache[n] = false;
        return false;        
    }
};

int main() {
    Solution s;
    s.canWinNim(1348820612);
}

0 个答案:

没有答案