为什么leetcode运行时结果与我的本地结果不同?

时间:2017-03-09 07:47:39

标签: c++ algorithm

这个问题与leetcode 403. Frog Jump

有关

leetcode运行时结果与我的本地结果不同。我使用动态编程策略和C ++语言来解决这个问题。以下是我的代码:

#include <iostream>
#include <vector>
#include <map>
#include <set>

using namespace std;

void print(vector<vector<bool>>& matrix) {
    for(auto row: matrix) {
        for(auto item: row) {
            cout << item << " ";
        }
        cout << endl;
    }
    cout << endl;
}

void eval(vector<int>& nums, map<int, int>& index, vector<vector<bool>>& dp, int i, int j) {
    auto i1 = index.find(nums[i] - (j - 1));
    if(i1 != index.end())
        dp[i][j] = (dp[i][j] || dp[i1->second][j - 1]);
    auto i2 = index.find(nums[i] - j);
    if(i2 != index.end())
        dp[i][j] = (dp[i][j] || dp[i2->second][j]);
    auto i3 = index.find(nums[i] - (j + 1));
    if(i3 != index.end())
        dp[i][j] = (dp[i][j] || dp[i3->second][j + 1]);
}

bool canCross(vector<int>& stones) {
    int n = stones.size();
    map<int, int> index;
    for(int i = 0; i < n; i++)
        index[stones[i]] = i;
    vector<vector<bool>> dp(n, vector<bool>(n, false));
    dp[0][1] = true;
    for(int i = 1; i < n; i++) {
        for(int j = 1; j < n; j++) {
            eval(stones, index, dp, i, j);
        }
    }
    print(dp);
    for(int i = 1; i < n; i++)
        if(dp[n - 1][i])
            return true;
    return false;
}

int main() {
    int val;
    vector<int> nums;
    while(cin >> val)
        nums.push_back(val);
    int res = canCross(nums);
    cout << res << endl;
    return 0;
}

测试用例:&#34; [0,1,2,3,4,5,6,12]&#34;

当我在本地运行我的代码时,它是正确的,输出:

0 1 0 0 0 0 0 0 
0 1 1 0 0 0 0 0 
0 1 1 0 0 0 0 0 
0 1 1 1 0 0 0 0 
0 1 1 1 0 0 0 0 
0 1 1 1 0 0 0 0 
0 1 1 1 1 0 0 0 
0 0 0 0 0 0 0 0 

0

我使用c ++ 11,并使用命令编译源代码:

  

g ++ -std = c ++ 11 -o test 403.cpp

gcc编译器版本信息是:

  

5.4.0 20160609(Ubuntu 5.4.0-6ubuntu1~16.04.4)

我在本地多次运行我的代码,结果总是如上所述。

但是当我将我的解决方案提交给leetcode oj时。它告诉我&#34;错误的anser&#34;:

Input:
[0,1,2,3,4,5,6,12]
Output:
true
Expected:
false
Stdout:
0 1 0 0 0 0 0 0 
0 1 1 0 0 0 0 0 
0 1 1 0 0 0 0 0 
0 1 1 1 0 0 0 0 
0 1 1 1 0 0 0 0 
0 1 1 1 0 0 0 0 
0 1 1 1 1 0 0 0 
0 0 0 0 0 0 0 1 

显然,出了点问题。也许我的解决方案不是这个问题的正确解决方案,但为什么leetcode运行时结果与我的本地结果不同?我不是一个经验丰富的编码员,我也不太了解Leetcode OJ机制。我谷歌关于这个并阅读Leetcode FAQ,我还没有得到答案。

如果知道我的问题的人可以解释我的代码发生了什么,请欣赏。

0 个答案:

没有答案
相关问题