Reputation: 113
I'm trying to write C++ code for solving house-robber problem.
But my recursion doesn't work, I'm getting Segmentation fault. Can't understand what's wrong. Please, take a look
int award(vector<int>& nums, int n, vector<int>& sum)
{
if (n == 0) sum[0] = 0;
if (n == 1) sum[1] = nums[0];
if (n > 1)
{
if ((sum[n-1]) < 0) sum[n-1] = award(nums,n-1,sum);
if ((sum[n-2]) < 0) sum[n-2] = award(nums,n-2,sum);
sum[n] = max(sum[n-2] + nums[n-1], sum[n-1]);
}
int ans = sum[n];
return ans;
}
int main()
{
vector<int> nums;
vector<int> sum (100);
int a;
int i = 0;
while (cin>>a)
{
nums[i] = a;
i++;
}
int n = nums.size();
for(int i = 0; i <= n; i++)
{
sum[i] = -1;
}
cout<<award(nums,n, sum);
}
Upvotes: 0
Views: 188
Reputation: 425
Let n = nums.size(). One problem is that your for loop is running from 0 to n, which is actually n+1 integers in a collection of size n. So one of them is out-of-range(and it is nums[n]).
An example: If n = 3, then 0,1,2,3 is a collection of 4 integers not 3.
Upvotes: 3