Leetcode BackTracking問題匯總

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗(yàn)。 張土汪:刷leetcod...
    土汪閱讀 12,921評論 0 33
  • LeetCode 刷題隨手記 - 第一部分 前 256 題(非會員),僅算法題,的吐槽 https://leetc...
    蕾娜漢默閱讀 18,392評論 2 36
  • 作為一個(gè)前端程序猿,下面這些站會讓你眼前一亮。 amazeui框架組建豐富 http://amazeui.org...
    歐巴冰冰閱讀 9,035評論 18 303
  • 實(shí)話實(shí)說—探索中國生態(tài)之路! 中國環(huán)保路線錯(cuò),都為環(huán)保來獻(xiàn)策; 環(huán)保理論西洋派,中國處處鬧災(zāi)害; 污水都往河里排,...
    科學(xué)新說閱讀 959評論 0 0
  • 蝴蝶花盛開的那年,沈初見一個(gè)人蹲在河邊看水里的魚游來游去。小時(shí)候的沈初見是一個(gè)較為木訥的孩子,所以同...
    桑樹非榆閱讀 562評論 0 1

友情鏈接更多精彩內(nèi)容