[leetcode] 39. Combination Sum 解题报告

题目链接:https://leetcode.com/problems/combination-sum/

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] 


思路:深搜+回朔。为保证结果有序,需要将vector首先排序,然后搜索的时候只能搜索本身或者比他大的数。思路比较清晰。写的时候还是忘记首先排序,以为他给的数据就是有序的,好坑!

代码如下:

class Solution {
public:
    void DFS(vector<int>& candidates, vector<int> vec, int target, int index, int sum)
    {
        if(sum > target)    return;
        if(sum == target)
        {
            result.push_back(vec);
            return;
        }
        for(int i = index; i < candidates.size(); i++)//每次添加一个数
        {
            vec.push_back(candidates[i]);
            DFS(candidates, vec,target, i, sum+candidates[i]);
            vec.pop_back();//分支结束后将这个数减去,即回溯
        }
    }

    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        sort(candidates.begin(), candidates.end());
        if(candidates.size() == 0 || target < candidates[0])
            return result;
        vector<int> vec;
        int sum = 0, index = 0;
        DFS(candidates, vec, target, index, sum);
        return result;
    }
private:
    vector<vector<int>> result;
};


你可能感兴趣的:(LeetCode,DFS,backtracking)