为什么我的代码在本地运行良好,但在 Leetcode 中却出现运行时错误(signed int 溢出)?

问题描述 投票:0回答:1

问题链接:https://leetcode.com/problems/combination-sum-iv/description/

这是我的 C++ 代码:

class Solution {
public:
    int combinationSum4(vector<int>& nums, int target) {
        vector<int> dp(target + 1, 0);
        dp[0] = 1;
        for (int i = 1; i <= target; ++i){
            for (int num : nums) {
                if (i >= num) {
                    dp[i] += dp[i - num];
                }
            }
        }
        return dp[target];
    }
};

错误: 第 9 行:字符 27:运行时错误:有符号整数溢出:2147483647 + 1 无法用类型“value_type”(又名“int”)表示(solution.cpp) 摘要:UndefinedBehaviorSanitizer:未定义行为解决方案.cpp:9:27

但是当我尝试在本地运行时,效果很好。

有人可以帮助我吗?谢谢洛特!!!!

图片在这里

c++ algorithm runtime-error
1个回答
0
投票

如果你检查一下约束条件,你就会得到解决方案。

std::vector<int64_t> dp(target + 1, 0);

-> 这将 dp 的数据类型更改为 int64_t,它可以处理比 int 大得多的数字。
试试这个,一定会成功的。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.