LeetCode Tag: Back tracking

LeetCode 93 Restore IP Addresses

Description

Given a string containing only digits, restore it by returning all possible valid IP address combinations.
For example:
Given "25525511135",
return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)

Solution

  1. 問題是要把一段字符串轉換成可能的ip地址
  2. 定義返回變量solutions
  3. 傳入restoreIp函數中
  • restoreIp 函數有四個參數原始的ip字符串、 返回結果solutions、idx(當前ip的索引)、restored、count(用來記錄切割的ip段, ip總共四段)
  • count > 4 就返回
  • count == 4 && idx == ip的長度,意味著完成了ip地址的轉換,并將存儲的變量restored 加入到 solutions中
  • 進行for循環 i = 1 2 3

如果idx+i > ip.length() 跳出循環
s = ip.substring(idx, idx+i)
s以0開始而且長度大于1 || i = 3&&s>256 跳過下一條語句
遞歸調用restoreIp(ip, solutions, idx移動i, restored + s + (count == 3 ? "" : "."), count +1);

Code

public class Solution {
    public List<String> restoreIpAddresses(String s) {
        List<String> solutions = new ArrayList<>();
        restoreIp(s, solutions, 0, "", 0);
        return solutions;
    }
    
    private void restoreIp(String ip, List<String> solutions, int idx, String restored, int count) {
        if(count > 4) return;
        if(count == 4 && idx == ip.length()) {
            solutions.add(restored);
        }
        for(int i = 1; i < 4; i++) {
            if(idx + i > ip.length()) break;
            String s = ip.substring(idx, idx+i);
            if ((s.startsWith("0") && s.length() > 1) || (i == 3 && Integer.parseInt(s) >= 256)) 
                continue;
            
            restoreIp(ip, solutions, idx+i, restored+s+(count == 3 ? "" : "."), count+1);
        }
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 背景 一年多以前我在知乎上答了有關LeetCode的問題, 分享了一些自己做題目的經驗。 張土汪:刷leetcod...
    土汪閱讀 12,766評論 0 33
  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,837評論 18 139
  • 50個常用的sql語句Student(S#,Sname,Sage,Ssex) 學生表Course(C#,Cname...
    哈哈海閱讀 1,248評論 0 7
  • 從來被教堅持,怎樣都要堅持,卻從沒有被教放棄。 所以,哪怕只有一線生機一絲可能,我們大概都會選擇堅持而不是放棄。 ...
    清韻難敲閱讀 500評論 0 0
  • 旅行與讀書,先有讀書,還是先有旅行?就如同先有雞還是先有蛋一般,在還未得到科學證明前,人們總是各有說辭,奇怪的是這...
    正記錄Beta閱讀 687評論 1 14