天天看點

leetcode-39. Combination Sum 組合總和

題目:

Given a set of candidate numbers (

candidates

) (without duplicates) and a target number (

target

), find all unique combinations in 

candidates

 where the candidate numbers sums to 

target

.

The same repeated number may be chosen from 

candidates

 unlimited number of times.

Note:

  • All numbers (including 

    target

    ) will be positive integers.
  • The solution set must not contain duplicate combinations.
Example 1:
Input: candidates =          [2,3,6,7],                 target =          7                ,
A solution set is:
[
  [7],
  [2,2,3]
]
      
Example 2:
Input: candidates = [2,3,5]         ,                 target = 8,
A solution set is:
[
  [2,2,2,2],
  [2,3,3],
  [3,5]
]      
給定一個無重複元素的數組 

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]
]      

思路:看到這種求所有解的情況,類似于排列組合,可以用dfs或者bfs。此題用dfs寫一個遞歸程式就可以求所有 可能情況了。

class Solution {
public:
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        vector<vector<int>> res;
        dfs(candidates,target,0,{},res);
        return res;
    }
    void dfs(vector<int>& candidates, int target,int start,vector<int> out,
             vector<vector<int>> &res)
    {
        if(target<0) return;
        else if(target==0) 
        {
            res.push_back(out);
            return;
        }
        for(int i=start;i<candidates.size();++i)
        {
            out.push_back(candidates[i]);
            dfs(candidates,target-candidates[i],i,out,res);
            out.pop_back();
        }
    }
};
           
class Solution:
    def combinationSum(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        def dfs(candidates,target,start,path,res):
            if target==0:
                return res.append(path+[])
            for i in range(start,len(candidates)):
                if target-candidates[i]>=0:
                    path.append(candidates[i])
                    dfs(candidates,target-candidates[i],i,path,res)
                    path.pop()
        
        res=[]
        dfs(candidates,target,0,[],res)
        return res
        
           

繼續閱讀