39. 組合總和 - 力扣(LeetCode)
需要定義一個index變量用來記錄訪問數組的下標,每次遞歸進行傳參,在搜索過程中,因為為了避免重復數據,而且允許一個元素的重復出現,傳入index時傳入當前遍歷的i值即可
class Solution {List<List<Integer>> list;List<Integer> res;int target;int count;public List<List<Integer>> combinationSum(int[] candidates, int target) {this.target = target;list = new ArrayList<>();res = new ArrayList<>();count = 0;dfs(candidates,0);return list;}public void dfs(int[] candidates,int index) {if (count == target) {list.add(new ArrayList<>(res));return;}for (int i = index; i < candidates.length; i++) {if (count + candidates[i] <= target) {res.add(candidates[i]);count += candidates[i];dfs(candidates,i);//回溯count -= candidates[i];res.remove(res.size() - 1);}}}
}