【Leetcode Summary】combination Sum

描述:給出一組數字,大於零且不重複。求這組數字中求和爲target的數字集合,集合中的數字可以重複出現

Example 1:

Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
  [7],
  [2,2,3]
]

本解法思路來源於:http://www.cnblogs.com/grandyang/p/4419259.html

solution:我們也可以不使用額外的函數,就在一個函數中完成遞歸,還是要先給數組排序,然後遍歷,如果當前數字大於target,說明肯定無法組成target,由於排過序,之後的也無法組成target,直接break掉。如果當前數字正好等於target,那麼當前單個數字就是一個解,組成一個數組然後放到結果res中。然後我們將當前位置之後的數組取出來,調用遞歸函數,注意此時的target要減去當前的數字,然後我們遍歷遞歸結果返回的二維數組,將當前數字加到每一個數組最前面,然後再將每個數組加入結果res即可,參見代碼如下:

class Solution {
public:
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        vector<vector<int>> res;
        vector<int> out;
        combinationSumDFS(candidates, target, 0, out, res);
        return res;
    }
    void combinationSumDFS(vector<int>& candidates, int target, int start, vector<int>& out, vector<vector<int>>& res) {
        if (target < 0) return;
        if (target == 0) {res.push_back(out); return;}
        for (int i = start; i < candidates.size(); ++i) {
            out.push_back(candidates[i]);
            combinationSumDFS(candidates, target - candidates[i], i, out, res);
            out.pop_back();
        }
    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章