public class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
List<List<Integer>> result = new LinkedList<>();
helper(result, new LinkedList<>(), candidates, target, 0);
return result;
}
private static void helper(List<List<Integer>> result, List<Integer> cur, int[] candidates, int target,int start) {
if(target>0){
for(int i = start;i<candidates.length&&target-candidates[i]>=0;i++){
cur.add(candidates[i]);
helper(result, cur, candidates, target-candidates[i], i);
cur.remove(cur.size()-1); // 關(guān)鍵的回退一步,要回到選擇前的狀態(tài)
}
}
else if(target==0){
result.add(new LinkedList<>(cur));
}
}
}
這類問題的大概思路都是尋找一條正確的路,當(dāng)遇到岔口時(shí),先嘗試一條路,走不通就依次返回上一個(gè)岔路,要注意回到岔路時(shí)要重置狀態(tài)。
cur.remove(cur.size()-1); // 關(guān)鍵的回退一步,要回到選擇前的狀態(tài)
就是這一句的意義。
當(dāng)有要求是不能重復(fù)的時(shí)候,要設(shè)置flag,或者設(shè)置boolean[],檢查是否被用過。
參考文章:https://segmentfault.com/a/1190000006121957
參考文章:https://siddontang.gitbooks.io/leetcode-solution/content/backtracking/permutation.html