LeetCode 39. 組合總和 40.組合總和II 131.分割迴文串

来源:https://www.cnblogs.com/cupxu/archive/2023/02/26/17156754.html
-Advertisement-
Play Games

歡迎關註個人公眾號:愛喝可可牛奶 LeetCode 39. 組合總和 40.組合總和II 131.分割迴文串 LeetCode 39. 組合總和 分析 回溯可看成對二叉樹節點進行組合枚舉,分為橫向和縱向 每次往sum添加新元素時,必須明確從can哪個位置開始,定義變數pos 返回條件 sum == ...


歡迎關註個人公眾號:愛喝可可牛奶

LeetCode 39. 組合總和 40.組合總和II 131.分割迴文串

LeetCode 39. 組合總和

分析

回溯可看成對二叉樹節點進行組合枚舉,分為橫向和縱向

每次往sum添加新元素時,必須明確從can哪個位置開始,定義變數pos

返回條件 sum == target 或 sum > target; 橫向結束條件 沒有新元素可以添加了即pos<can.length;

bt(can, sum, tar, pos){
	if(sum == tar) add return;
    if(sum > tar) pos++ return;
    for(int i = pos; i < can.len;i++){
        sum+=can[pos];
        bt(can, sum, tar, i);
        sum-=can[pos];
    }
}

這個回溯考慮sum > tar時, pos++不應該寫在第3行,這樣導致回溯減掉的元素值與遞歸添加的不一樣。而應該放在第4行for()中,只有當縱向回溯結束時(也就是很多個sum+=can[i]導致return後),橫向遍歷才會往右移動;回溯第n個can[i] 回溯第n-1個can[i];

剪枝

一次回溯只能抵消一層遞歸;每次return只是從已經添加進sum的眾多can[i]中減掉一個

舉個慄子:

sum+= n個can[i],回溯一次還剩n-1個can[i];這時要i++了;但是剩下的sum和這個i++後的新can[i]加起來可能也會超過tar,這步操作可以剪枝,避免進入新can[i]的遞歸;

for (int i = pos; i < candidates.size() && sum + candidates[i] <= target; i++)

代碼

class Solution {
    List<List<Integer>> res = new ArrayList<>();
    LinkedList<Integer> path = new LinkedList();
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        
        Arrays.sort(candidates); // 先進行排序
        backtracking(candidates, target, 0, 0);
        return res;
    }

    public void backtracking(int[] candidates, int target, int sum, int idx) {
        // 找到了數字和為 target 的組合
        if (sum == target) {
            res.add(new ArrayList<>(path));
            return;
        }

        for (int i = idx; i < candidates.length; i++) {
            // 如果 sum + candidates[i] > target 就終止遍歷
            if (sum + candidates[i] > target) break;
            path.add(candidates[i]);
            backtracking(candidates, target, sum + candidates[i], i);
            path.removeLast(); // 回溯,移除路徑 path 最後一個元素
        }
    }
}

LeetCode 40.組合總和II

分析

在原有基礎上設限每個數字在每個組合中只能使用 一次 且不包含重覆的組合

Arrays升序;縱向遍歷時就要i++;Set去重

Set去重超時了!!! 要在添加集合的時候就判斷是否重覆,取res中最後一個path和當前滿足條件的path比較 也不行

縱向遞歸不需要去重,橫向遞歸時採用去重

代碼

class Solution {
    List<List<Integer>> res = new LinkedList();
    LinkedList<Integer> path = new LinkedList();
    int sum = 0;
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates); // 先進行排序
        backtracking(candidates, target, 0);
        return res;
    }

    public void backtracking(int[] candidates, int target, int idx) {
        // 找到了數字和為 target 的組合
        if (sum == target) {
            res.add(new LinkedList<>(path));
            return;
        }

        for (int i = idx; i < candidates.length && sum + candidates[i] <= target; i++) {
            // 要對橫向遍歷時使用過的元素進行跳過 因為一樣的元素在深度遞歸時已經把包含此元素的所有可能結果全部枚舉過了
            if (i > idx && candidates[i] == candidates[i - 1]) {
                continue;
            }
            path.add(candidates[i]);
            sum += candidates[i];
            //System.out.println("sum="+sum);
            //i++;
            backtracking(candidates, target, i+1);
            //i--;
            //sum -= candidates[i];
            sum-=path.getLast();
            path.removeLast(); // 回溯,移除路徑 path 最後一個元素
        }
    }
}

LeetCode 131.分割迴文串

分析

切割子串,保證每個子串都是 迴文串

找到所有的子串組合,判斷子串是否是迴文串,根據索引切割 startIndex endIndex if(start-end) is ; res.add

代碼

class Solution {
    List<List<String>> res = new ArrayList<>();
    LinkedList<String> path = new LinkedList<>();

    public List<List<String>> partition(String s) {
        backTracking(s, 0);
        return res;
    }

    private void backTracking(String s, int startIndex) {
        //如果起始位置大於s的大小,說明找到了一組分割方案
        if (startIndex >= s.length()) {
            res.add(new ArrayList(path));
            return;
        }
        for (int i = startIndex; i < s.length(); i++) {
            //如果是迴文子串,則記錄
            if (isPalindrome(s, startIndex, i)) {
                String str = s.substring(startIndex, i + 1);
                path.add(str);
            } else {
                continue;
            }
            //起始位置後移,保證不重覆
            backTracking(s, i + 1);
            // 一定要有回溯 開始下一種分割
            path.removeLast();
        }
    }
    //判斷是否是迴文串
    private boolean isPalindrome(String s, int startIndex, int end) {
        for (int i = startIndex, j = end; i < j; i++, j--) {
            if (s.charAt(i) != s.charAt(j)) {
                return false;
            }
        }
        return true;
    }
}

總結

  1. 題目給定的數據集如果使用數組的方式,要判斷是否有序,沒有說明有序最好視情排序
  2. 回溯橫向移動的時機一定是某個縱向遞歸結束
  3. 看清題目要求,將串的所有子串都分割成迴文子串
  4. 橫向遍歷邏輯 縱向遞歸startIndex++邏輯 回溯邏輯

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 面向對象進階第三天 內部類 內部類是什麼? 類的5大成分(成員變數、成員方法、構造器、代碼塊、內部類)之一 類中的類 使用場景 當一個事物的內部,還有一個部分需要一個完整的結構進行描述時。 內部類有幾種 1、靜態內部類 是什麼?有static修飾,屬於外部類本身。 特點:只是位置在類裡面。類有的成分 ...
  • 模板 函數模板 template<typename T1,typename T2,……> 定義了必須使用,否則報錯 template<typename T> T add(T a,T b) { return a + b; } 根據具體的使用情況生成模板函數 add(1.1,2.1); //生成doub ...
  • 一、繼承的基本概念 ​ 繼承:子類繼承父類的屬性和行為 ​ 作用:代碼復用 繼承分類: 1. 按訪問屬性分為public、private、protected三類 1)public: 父類屬性無更改,pubic, private, protected 仍是自己本身(子類成員函數可以訪問父類的publi ...
  • 引言 使用Spring Innitializer創建SpringBoot項目 解決方案 引言 筆者使用的IDEA版本為2020.2.4, 在使用Spring Innitializer創建SpringBoot項目後, SpringBoot項目無法被識別IDEA正常識別, 本文將來解決這個問題. 使用S ...
  • 1、錯誤提示信息如下: com.alibaba.fastjson.JSONException: exepct '[', but string, pos 4, json : "[{"attrId":33,"attrName":"粗跟"},{"attrId":44,"attrName":"厚底"}]" ...
  • Java流程式控制制:用戶交互Scanner、選擇結構 用戶交互Scanner Scanner類用於獲取用戶的輸入 基本語法: Scanner s = new Scanner(System.in);s.close(); package com.qiu.first.scanner;​import java ...
  • 1 func absInt(x int) int { 2 if x < 0 { 3 return -x 4 } 5 return x 6 } 下麵會用到此方法, int類型值取絕對值 1 type sp_item struct { 2 x int 3 y int 4 g int 5 h int 6 ...
  • (Java刷題常用的數據結構總結) 1. 基礎運算 //int型相關操作 Integer.INT_MAX;//int型最大值 Integer.INT_MIN;//int型最小值 long name;//註意:沒有c語言裡面的long long (int)n1%(int)n2;//取餘運算,針對int ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...