Problem Statement: Given n items with size Ai, an integer m denotes the size of a backpack. How full you can fill this backpack?
Example Example 1: Input: [3,4,8,5], backpack size=10 Output: 9
Example 2: Input: [2,3,5,7], backpack size=12 Output: 12
I have to write solution using memoization , I know bottom up dp will be quite fast ,But can you help me with other optimisation that i can add in this solution.
class Solution {
public:
unordered_map<string,int>m1;
int solve(int m,vector<int>&a,int i){
if(i<0)return 0;
string s = to_string(m)+" "+to_string(i);
if(m1.count(s))return m1[s];
int val=0;
if(m-a[i]>=0)val = a[i] + solve(m-a[i],a,i-1);
return m1[s]=max(val,solve(m,a,i-1));
}
int backPack(int m, vector<int> &a) {
// write your code here
return solve(m,a,int(a.size()-1));
}
};