一、題目描述
給定一個無重復元素的陣列 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]
]
提示:
1 <= candidates.length <= 30
1 <= candidates[i] <= 200
candidate 中的每個元素都是獨一無二的,
1 <= target <= 500
二、解題思路
對于這類尋找所有可行解的題,我們都可以嘗試用「搜索回溯」的方法來解決,
回到本題,我們定義遞回函式 dfs(target, combine, idx) 表示當前在 candidates 陣列的第 idx 位,還剩 target 要組合,已經組合的串列為 combine,遞回的終止條件為 target <= 0 或者 candidates 陣列被全部用完,那么在當前的函式中,每次我們可以選擇跳過不用第 idx 個數,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/252667.html
標籤:java
下一篇:java繪制五子棋棋盤
