Im trying to solve a leetcode problem called Partition Equal Subset Sum So basically we are given an array of some integers an we need to find out if we can create a subset of equal sum based on the array, for example [1, 5, 11, 5] can be divided into equal sum with [1,5,5] and [11] since the sum of both are equal.
I tried using recursion to solve this problem but the problem is that the boolean variable hasil
doesn't update itself when given a new value. It just returns the value that I gave it in the declaration, so for example if I declare hasil = true
, then the return value will always be true.
#include <bits/stdc++.h>
#define ll long long
#define pb push_back
using namespace std;
bool solve(vector<int>& nums, int sum1, int sum2, int index){
bool hasil = false;
if(index != nums.size() ){
solve(nums,sum1+nums[index],sum2,index + 1);
solve(nums,sum1,sum2+nums[index],index + 1);
}
if(sum1 == sum2 && index == nums.size() ){
//cout << sum1 << " " << sum2 << endl;
hasil = true;
//return hasil;
} else if(sum1 != sum2 && index == nums.size() ){
//cout << sum1 << " " << sum2 << endl;
hasil = false;
//return hasil;
}
return hasil;
//hasil will always return as in declaration, in this case it's false
}
int main()
{
vector<int> nums{ 1,5,11,5 };
int sum1 = 0;
int sum2 = 0;
int index = 0;
return solve(nums,sum1,sum2,index);
}