Restore IP Addresses

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)

ref: http://www.cnblogs.com/feiling/p/3301869.html

public static ArrayList<String> restoreIpAddresses(String s) {
        // Start typing your Java solution below
        // DO NOT write main() function
        ArrayList<String> result = new ArrayList<String>();
        if (s == null || s.length() == 0) {
            return result;
        }
        int depth = 0, start = 0;
        String ip = "";
        generate(s, start, depth, result, ip);

        return result;
    }

    private static void generate(String s, int start, int depth,
            ArrayList<String> result, String ip) {
        // max = 3 check it
        if ((s.length() - start) > (4 - depth) * 3) {
            return;
        }
        // min = 1 check it
        if (s.length() - start < 4 - depth) {
            return;
        }
        if (depth == 4) {
            ip = ip.substring(0, ip.length() - 1);
            if(!result.contains(ip))
                result.add(ip);
            return;
        }

        int num = 0;
        for (int i = start; i < Math.min(start + 3, s.length()); i++) {
            num = num * 10 + (s.charAt(i) - '0');
            if (num <= 255) {
                generate(s, i + 1, depth + 1, result, ip + num + ".");
            }
            if(num == 0){
                break;
            }
        }
    }
原文地址:https://www.cnblogs.com/RazerLu/p/3544620.html