题目

Given a set of candidate numbers (C) (without duplicates) 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.
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]
]

思路

本题是典型的回溯法,基本思路就是排序,回溯,但是要注意,数值可以被使用多次,所以回溯时要注意代码中i不变

backtrack(candidates,cur,i,target-candidates[i]);

代码

class Solution {
public:
    vector<vector<int>> res;
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        vector<int> cur;
        sort(candidates.begin(),candidates.end());
        backtrack(candidates,cur,0,target);
        return res;

    }
private:
    void backtrack(vector<int> candidates,vector<int> cur,int start ,int target)
    {
        if(target==0)
        {
            res.push_back(cur);
        }
        else
        {
            for(int i=start;i<candidates.size()&&candidates[i]<=target;i++)
            {
                cur.push_back(candidates[i]);
                backtrack(candidates,cur,i,target-candidates[i]);
                cur.pop_back();
            }
        }
    }

};