目錄
- 1、題目
- 2、思路
- 3、c++代碼
- 4、java代碼
1、題目
給定一個無重復元素的正整數陣列 candidates 和一個正整數 target ,找出 candidates 中所有可以使數字和為目標數 target 的唯一組合,
candidates 中的數字可以無限制重復被選取,如果至少一個所選數字數量不同,則兩種組合是唯一的,
對于給定的輸入,保證和為 target 的唯一組合數少于 150 個,
示例 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]]
示例 3:
輸入: candidates = [2], target = 1
輸出: []
示例 4:
輸入: candidates = [1], target = 1
輸出: [[1]]
示例 5:
輸入: candidates = [1], target = 2
輸出: [[1,1]]
提示:
1 <= candidates.length <= 301 <= candidates[i] <= 200candidate中的每個元素都是獨一無二的,1 <= target <= 500
2、思路
(dfs,遞回)
遞回列舉,列舉每個數字可以選多少次,
遞回程序如下:
- 1、遍歷陣列中的每一個數字,
- 2、遞回列舉每一個數字可以選多少次,遞回程序中維護一個
target變數,如果當前數字小于等于target,我們就將其加入我們的路徑陣列path中,相應的target減去當前數字的值,也就是說,每選一個分支,就減去所選分支的值, - 3、當
target == 0時,表示該選擇方案是合法的,記錄該方案,將其加入res陣列中,
遞回樹如下,以candidates = [2,3,6,7], target = 7為例,

最終答案為:[[7],[2,2,3]] ,但是我們發現[[2, 2, 3], [2, 3, 2], [3, 2, 2]方案重復了,為了避免搜索程序中的重復方案,我們要去定義一個搜索起點,已經考慮過的數,以后的搜索中就不能出現,讓我們的每次搜索都從當前起點往后搜索(包含當前起點),直到搜索到陣列末尾,這樣我們人為規定了一個搜索順序,就可以避免重復方案,
如下圖所示,處于黃色虛線矩形內的分支都不再去搜索了,這樣我們就完成了去重操作,

遞回函式設計:
void dfs(vector<int>&c,int u ,int target)
變數u表示當前列舉的數字下標,target是遞回程序中維護的目標數,
遞回邊界:
- 1、
if(target < 0),表示當前方案不合法,回傳上一層, - 2、
if(target == 0),方案合法,記錄該方案,
時間復雜度分析: 無
3、c++代碼
class Solution {
public:
vector<vector<int>>res; //記錄答案
vector<int>path; //記錄路徑
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
dfs(candidates,0,target);
return res;
}
void dfs(vector<int>&c,int u ,int target)
{
if(target < 0) return ; //遞回邊界
if(target == 0)
{
res.push_back(path); //記錄答案
return ;
}
for(int i = u; i < c.size(); i++){
if( c[i] <= target)
{
path.push_back(c[i]); //加入路徑陣列中
dfs(c,i,target - c[i]);// 因為可以重復使用,所以還是i
path.pop_back(); //回溯,恢復現場
}
}
}
};
4、java代碼
class Solution {
List<List<Integer>> res = new ArrayList<>(); //記錄答案
List<Integer> path = new ArrayList<>(); //記錄路徑
public List<List<Integer>> combinationSum(int[] candidates, int target) {
dfs(candidates,0, target);
return res;
}
public void dfs(int[] c, int u, int target) {
if(target < 0) return ;
if(target == 0)
{
res.add(new ArrayList(path));
return ;
}
for(int i = u; i < c.length; i++){
if( c[i] <= target)
{
path.add(c[i]);
dfs(c,i,target - c[i]); // 因為可以重復使用,所以還是i
path.remove(path.size()-1); //回溯,恢復現場
}
}
}
}
原題鏈接: 39. 組合總和

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/290861.html
標籤:java
