leetcode刷题,总结,记录,备忘 39

Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • Elements in a combination (a1a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
  • The solution set must not contain duplicate combinations.

For example, given candidate set 2,3,6,7 and target 7
A solution set is: 
[7] 

[2, 2, 3] 

递归回溯,这个题目不难,,,我自己稍微折腾了下,ac了一个递归的解法,,但是耗时实在太恐怖了,去看看了人家的解法,,用深度优先,,才十几毫秒,差的非常多,感觉自己还是有点蠢。。。

解题思路就是遍历数组,判断目标数和当前数的大小关系,目标数小于当前数就跳过,大于就用目标数减去当前数,进行递归,等于的话就相当于找到了解,讲数字放入数组,以次往复即可,思路还是比较清晰的。先上自己400多毫秒的解法。

class Solution {
public:
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
       vector<vector<int> > result;
       if (candidates.size() == 0)
       {
           return result;
       }
       
       for (int i = 0; i < candidates.size(); ++i)
       {
           if (candidates[i] > target)
           {
               continue;
           }
           else if (candidates[i] == target)
           {
               vector<int> temp;
               temp.push_back(target);
               result.push_back(temp);
           }
           else if (candidates[i] < target)
           {
               vector<vector<int> > tr = combinationSum(candidates, target - candidates[i]);
               if (tr.size() != 0)
               {
                   for (int j = 0; j < tr.size(); ++j)
                   {
                       tr[j].push_back(candidates[i]);
                       sort(tr[j].begin(), tr[j].end());
                       result.push_back(tr[j]);
                   }
               }
           }
       }
       
       set<vector<int> > svi(result.begin(), result.end());
       vector<vector<int> > r(svi.begin(), svi.end());
       return r;
    }
};

感觉这个还是很蠢的,看了别人的深度优先解法,,,其实自己之前也接触过,很快就看懂了,但是自己解题的时候技师没有联想到,,需要更敏感一点。下面上深度优先的解法,,耗时16毫米,,与我自己的愚蠢解法快了好多。

class Solution {
public:
    vector<vector<int> > result;
    vector<int> temp;
    
    
    void function(vector<int> & candidates, int target, int deep)
    {
        if (target == 0)
        {
            result.push_back(temp);
            return;
        }
        
        for (int i = deep; i < candidates.size() && target - candidates[i] >= 0; ++i)
        {
            temp.push_back(candidates[i]);
            function(candidates, target - candidates[i], i);
            temp.pop_back();
        }
    }
    
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        sort(candidates.begin(), candidates.end());
        
        function(candidates, target, 0);
        
        return result;
    }
    
};



你可能感兴趣的:(leetcode刷题,总结,记录,备忘 39)