I just solved the subset sum problem:
Given an integer array
nums
of sizeN
. You are also given an integerB
, you need to find whether there exists a subset innums
whose sum isB
. If there exist a subset then return1
else return0
.Constraints are:
1 <= N <= 100
;1 <= nums[i] <= 100
;1 <= B <= 10^5
;
The way I solved this problem is as below (0/1 knapsack):
vector<int> n;
int t;
unordered_map<string, long long> m;
int helper(int i, int sum) {
if(i>=n.size()) return sum==t;
string str=to_string(i)+"-"+to_string(sum);
if(m.count(str)) return m[str];
int val=helper(i+1, sum+n[i]);
val=max(val, helper(i+1, sum));
return m[str]=val;
}
int Solution::solve(vector<int> &nums, int B) {
n=nums;
t=B;
m.clear();
return helper(0,0);
}
This gets "Accepted". However, note that all the values in nums
are positive; so IMO sum will only remain the same/go on increasing. i
goes on increasing, too. So, we will never encounter a value previously stored in the memoization table.
But, if I remove memoization, it results in Wrong Answer for some large test case. What am I missing? Will any recursive call ever encounter a previous state?