39. 组合总和 + 40.

菜鸟级别,还需要参考别人的思路:
https://blog.csdn.net/zr1076311296/article/details/51374923

思路:递归,但是具体实现细节还是需要参考别人的代码。
递归整体思路应该就是昨天和今天这两个。一个是带返回值,一个在参数传递时改变。

class Solution {
public:
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        sort(candidates.begin(), candidates.end());
        vector<vector<int>> res;
        vector<int> temp;
        findAll(candidates, res,temp,target,0);
        return res;
    }
    void findAll(const vector<int>& candidates, vector<vector<int>>& res, vector<int>& temp, int target, int index)
    {
        if (target == 0) {
            res.push_back(temp);
            return;
        } 

        if (target < candidates[0]){
            return;
        }

        for(int i = index; i < candidates.size(); ++i){
            temp.push_back(candidates[i]);
            findAll(candidates, res, temp, target-candidates[i],i);
            temp.pop_back(); 
            }
        }
};

40.

1.

i换成i+1;

2.

while(i < candidates.size()-1 && candidates[i] == candidates[i+1]){  
    i++;
}

解答:

class Solution {
public:
    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        sort(candidates.begin(), candidates.end());
        vector<int> temp;
        vector<vector<int>> res;
        func(candidates, temp, res, target, 0);
        return res;
    }

    void func(vector<int>& candidates, vector<int>& temp, vector<vector<int>>& res, int target, int index){
        for (int i = index; i < candidates.size(); i++){

            if (target == candidates[i]) {
                temp.push_back(candidates[i]);
                res.push_back(temp);
                temp.pop_back();
                return;
            }
            if(target < candidates[i]){
                return;
            }else{
                temp.push_back(candidates[i]);
                func(candidates, temp, res, target-candidates[i], i+1);
                temp.pop_back();
                while(i < candidates.size()-1 && candidates[i] == candidates[i+1]){  
                    i++;
                }
            }

        }
    }
};

你可能感兴趣的:(leetcode)