93. Restore IP Addresses 93.恢复IP地址

Given a string containing only digits, restore it by returning all possible valid IP address combinations.

A valid IP address consists of exactly four integers (each integer is between 0 and 255) separated by single points.

Example:

Input: "25525511135"
Output: ["255.255.11.135", "255.255.111.35"]

思路:DFS是分成四个部分 又是剩下的继续分的思路。怎么选择end的位数啊?1、2、3位都要选吗?是的呢。
for循环的字符串长度和section的增加都在DFS中完成
generateIpAddresses(s, sec + 1, currentLength + i,

添加完就行了,加个return ;


        if (sec == 4 && currentLength == s.length()) {
            result.add(curIP);
            return ;
        }

class Solution {
    public List<String> restoreIpAddresses(String s) {
        List<String> result = new ArrayList<>();
        
        //cc
        if (s == null || s.length() == 0)
            return  result;
        
        //dfs, add to a List<String>, return void
        dfs(s, 0, 0, "", result);
        
        //return
        return result;
    }
    
    public void dfs(String s, int sec, int currentLength, String currentIP, 
                           List<String> result) {        
        //exit
        if (sec > 4)
            return ;
        
        if (sec == 4 && currentLength == s.length()) {
            result.add(currentIP);
            return ;
        }
        
        for (int i = 1; i <= 3; i++) {
            //cc
            if (currentLength + i > s.length())
                return;
            
            String sectionIP = s.substring(currentLength, currentLength + i);
            
            if ((sectionIP.length() > 1 && sectionIP.charAt(0) == '0') || 
                (Integer.valueOf(sectionIP) > 255))
                break;
            
            dfs(s, sec + 1, currentLength + i, 
                currentIP == "" ? sectionIP: currentIP + "." + sectionIP, 
                result);
        }
    }
}
View Code

原文地址:https://www.cnblogs.com/immiao0319/p/13287044.html