93. Restore IP Addresses

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"]

DFS求解,程序如下所示:

class Solution {
    StringBuilder sb = new StringBuilder();
    public List restoreIpAddresses(String s) {
        List list = new ArrayList<>();
        dfs(s, s.length(), 0, 0, list);
        return list;
    }
    
    public void dfs(String s, int len, int begin, int cur, List list){
        if (begin >= len){
            if (cur == 4){
                String str = sb.toString();
                list.add(str.substring(0, str.length() - 1));
            }
            return;
        }
        if (cur > 4){
            return;
        }
        for (int i = begin; i < len; ++ i){
            String tmp = s.substring(begin, i+1);
            if (i+1 - begin >= 4){
                break;
            }
            if (i+1 - begin >= 2 && tmp.charAt(0) == '0'){
                continue;
            }
            int val = Integer.parseInt(tmp);
            if (val < 256){
                sb.append(tmp + ".");
                dfs(s, len, i+1, cur + 1, list);
                sb.delete(sb.length() - tmp.length() - 1, sb.length());
            }
        }
    }
}

 

你可能感兴趣的:(LeetCode)