1. 程式人生 > >Leetcode ---- 組合總和

Leetcode ---- 組合總和

題目:

給定一個無重複元素的陣列 candidates 和一個目標數 target ,找出 candidates 中所有可以使數字和為 target 的組合。

candidates 中的數字可以無限制重複被選取。

說明:

  • 所有數字(包括 target)都是正整數。
  • 解集不能包含重複的組合。 

示例 1:

輸入: candidates = [2,3,6,7], target = 7,
所求解集為:
[
  [7],
  [2,2,3]
]

示例 2:

輸入: candidates = [2,3,5], target = 8,
所求解集為:
[
  [2,2,2,2],
  [2,3,3],
  [3,5]
]

思路:

這道題採用回溯法。先將問題簡化,當棧中元素求和等於 sum 時輸出,大於則返回,小於則繼續累計。由於該題的每個元素可以無限次使用,且子解不能重複,則我們會選用 j 進入下個迴圈。這樣,每個數都會多次訪問,且回溯時不會交叉子解。

程式:

class Solution {
public:
    vector<vector<int>> res;
    vector<int> tmpv;
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        dfs(candidates,0,target,0);
        
        return res;
    }
    
    
    void dfs(vector<int> num, int sum, int target, int i){
        if (sum == target){
            res.push_back(tmpv);
            return;
        }
        else if (sum > target)
            return;
        for (int j=i;j<num.size();j++){
            tmpv.push_back(num[j]);
            dfs(num,sum+num[j],target,j);
            tmpv.pop_back();
        }        
        
    }
};