knakul853

Untitled

Jun 21st, 2020
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.06 KB | None | 0 0
  1. /**
  2. knakul853
  3. **/
  4. class Solution {
  5. public:
  6.     int findTargetSumWays(vector<int>& nums, int S) {
  7.        
  8.         int n = nums.size();
  9.         int sm = accumulate(nums.begin(), nums.end(), 0);
  10.        
  11.         if(sm < S || ((sm + S) &1))return 0;
  12.         return f(nums, (sm + S)/2);
  13.        
  14.        
  15.     }
  16.    
  17.     int f(vector<int>& nums, int s)
  18.     {
  19.         vector<int>dp(s+1,0);
  20.         dp[0] = 1;
  21.        
  22.         for(auto num:nums)
  23.         {
  24.             for(int j=s;j>=num;j--)
  25.             {
  26.                 dp[j]+=dp[j-num];
  27.             }
  28.         }
  29.         return dp[s];
  30.     }
  31.    
  32.    
  33. };
  34.  
  35. class Solution {
  36. public:
  37.     int findTargetSumWays(vector<int>& nums, int S) {
  38.        
  39.         int n = nums.size();
  40.         return f(nums, n, 0, 0, S);
  41.        
  42.     }
  43.    
  44.     int f(vector<int>& nums, int n, int sm,int id, int s)
  45.     {
  46.         if(id == n && s == sm)
  47.         {
  48.             return 1;
  49.         }
  50.         if(id==n)return 0;
  51.        
  52.         return f(nums, n, sm+nums[id], id+1, s) + f(nums,n, sm - nums[id], id+1, s);
  53.     }
  54. };
Add Comment
Please, Sign In to add comment