Search code examples
c++dynamic-programmingbacktracking

Leetcode Prob No. 494 Target Sum ,,,,,Getting Runtime Error


In this code,i was getting this error... for input nums =

 Line 1034: Char 34: runtime error: addition of unsigned offset to 0x6250004d0900 overflowed to 0x6250004cf960 (stl_vector.h)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:1043:34

//Incorrect code
class Solution {
public:
    
    int fun(vector<int>& nums, int target,int n ,vector<vector<int>> &dp){
        if(n  == 0){
            if(target == 0) return 1;
            return 0;
            }
        
        if(dp[n][target+1000] != -1) return dp[n][target+1000];
        return dp[n][target+1000] =  fun(nums,target - nums[n-1],n-1,dp) + fun(nums,target + nums[n-1],n-1,dp);
    }
    int findTargetSumWays(vector<int>& nums, int target) {
       vector<vector<int>> dp(21,vector<int>(2001,-1));
       return fun(nums,target,nums.size(),dp);
    }
};

After getting runtime. error in prev approach, i tried 2nd approach just by reversing the way of traversing the vector nums from N->0 to 0->N, and the code successfully got submitted. What was the problem in the previous code???

//Correct code
class Solution {
public:
    int dp[21][2001];

    int fun(int i,int sum,int target,vector<int>&nums){
        if(i == nums.size()){
            if(sum == target) return 1;
            return 0;
        }
        if(dp[i][sum+1000] != -1) return dp[i][sum+1000];
        return dp[i][sum+1000]  = fun(i+1,sum+nums[i],target,nums) + fun(i+1,sum-nums[i],target,nums);  
    }

    int findTargetSumWays(vector<int>& nums, int target) {
        memset(dp,-1,sizeof(dp));
        return fun(0,0,target,nums);
    }
};

Solution

  • According to the problem page

    Target Sum - LeetCode

    The value of the input target may become -1000.

    With this value, after the calculation target - nums[n-1], the index target+1000 may go below zero with the new value of the argument target, and this is an out-of-range access.

    You have to allocate enough elements and use proper offset to avoid this error.