A 16ms c++ solution


  • 0
    class Solution {
      public:
    bool recive(vector<int>& candidates, vector<int>& t, int k, int target)
    {
    	for (int i = k; i<candidates.size(); i++)                    
    	{
    		if (target - candidates[i]>0)
    		{
    			t.push_back(candidates[i]);
    			if (!recive(candidates, t, i, target - candidates[i]))
    				t.pop_back();
    			
    		}
    		else if (target - candidates[i] == 0)
    		{
    			t.push_back(candidates[i]);
    			res.push_back(t);
    			t.pop_back();
    
    		}
    		else if (target - candidates[i]<0)
    			return false;
    	}
    	return false;
    }
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
    	sort(candidates.begin(), candidates.end());
    	int temp = target;
    	for (int i = 0; i<candidates.size(); i++)
    	{
    		vector<int> t;
    		if (candidates[i] == target)
    		{
    			t.push_back(candidates[i]);
    			res.push_back(t);
    			continue;
    		}
    		else if (candidates[i]>target)
    			return res;
    		else if (candidates[i]<target)
    		{
    			t.push_back(candidates[i]);
    			recive(candidates, t, i, target - candidates[i]);
    		}
    
    		// temp=target;
    	}
    	return res;
    }
    
    private:
    vector<vector<int>> res;
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.