Advertisement
surajmateti

Untitled

Sep 7th, 2021
945
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.88 KB | None | 0 0
  1. class Solution {
  2.     vector<vector<int>>ans;
  3.     void fun(int i, int n , int target , vector<int>&a , vector<int>tp)
  4.     {  
  5.         if(target < 0) return;
  6.         if(target == 0)
  7.         {
  8.             ans.push_back(tp);
  9.             return ;
  10.         }
  11.         if(i == n-1)
  12.         {
  13.            if(target % a[i] == 0)
  14.            {
  15.                int times = target/a[i];
  16.                while(times>0)
  17.                {
  18.                    tp.push_back(a[i]); times--;
  19.                }
  20.                ans.push_back(tp);
  21.            }
  22.            return ;
  23.         }
  24.         tp.push_back(a[i]); fun(i,n,target - a[i],a,tp);
  25.         tp.pop_back();
  26.         fun(i+1,n,target,a,tp);
  27.     }
  28. public:
  29.     vector<vector<int>> combinationSum(vector<int>& a, int target) {
  30.         int n = a.size();
  31.         vector<int>tp;
  32.         fun(0,n,target,a,tp);
  33.         return ans;
  34.     }
  35. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement