Advertisement
Singasking

Untitled

Jan 19th, 2023
846
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.84 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int f(int index,int target,vector<int> &nums,vector<vector<int>> &dp) {
  4.      
  5.       //  if(target<0) return 0;
  6.  
  7. if(index==0) {
  8.     if(nums[index]==target && target==0) return 2;
  9.     if(nums[index]==target ) return 1;
  10.     if(target==0) return 1;
  11.     return 0;
  12.  
  13. }
  14. if(dp[index][abs(target)]!=-1) return dp[index][abs(target)];
  15.  
  16.     int take = (target-nums[index]>=0)?f(index-1,target-nums[index],nums,dp):0;
  17.     int ntake = f(index-1,target,nums,dp);
  18.     return dp[index][abs(target)]= take + ntake;
  19.  
  20.     }
  21.     int findTargetSumWays(vector<int>& nums, int target) {
  22.         int s=0;
  23.         for(auto x:nums) s+=x;
  24.         if((target+s)%2!=0) return 0;
  25.         vector<vector<int>> dp(nums.size(),vector<int>((abs(target)+s)/2+2,-1));
  26.         return f(nums.size()-1,(target+s)/2,nums,dp);
  27.      
  28.     }
  29. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement