1. 程式人生 > >39. 組合總和 + 40.

39. 組合總和 + 40.

思路:遞迴,但是具體實現細節還是需要參考別人的程式碼。
遞迴整體思路應該就是昨天和今天這兩個。一個是帶返回值,一個在引數傳遞時改變。

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++;
                }
            }

        }
    }
};