Problem

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

Example:

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

Solution

class Solution {
    public List<String> restoreIpAddresses(String s) {
        //4 segments, 0-255, dfs from 0 to len-1
        List<String> res = new ArrayList<>();
        dfs(s, 0, 0, "", res);
        return res;
    }
    private void dfs(String str, int index, int count, String temp, List<String> res) {
        int n = str.length();
        if (count == 4 && index == n) {
            res.add(temp);
            return;
        }
        if (count > 4 || index > n) return;
        for (int i = 1; i <= 3; i++) {
            if (index+i > n) break;
            String part = str.substring(index, index+i);
            if (part.startsWith("0") && part.length() != 1 ||
               Integer.parseInt(part) > 255) continue;
            String cur = temp+part;
            if (count != 3) cur += ".";
            dfs(str, index+i, count+1, cur, res);
        }
    }
}

linspiration
161 声望53 粉丝