zoukankan      html  css  js  c++  java
  • LeetCode

    题目:

    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)

    思路:

    递归,然后判断是否是合法的1/4部分

    package recursion;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class RestoreIPAddresses {
    
        public List<String> restoreIpAddresses(String s) {
            List<String> res = new ArrayList<String>();
            dfs(res, "", s, 1);
            return res;
        }
        
        private void dfs(List<String> res, String t, String s, int k) {
            if (k == 4) {
                if (isValid(s))
                    res.add(t + s);
            } else {
                int n = s.length();
                for (int i = 1; i <= 4; ++i) {
                    if (n >= i && isValid(s.substring(0, i))) {
                        dfs(res, t + s.substring(0, i) + ".", s.substring(i, n), k + 1);
                    }
                }
            }
        }
        
        private boolean isValid(String s) {
            if (s.length() > 0 && s.length() <= 3) {
                if (s.length() > 1 && s.charAt(0) == '0') return false;
                int value = Integer.parseInt(s);
                if (value <= 255) return true;
            }
            return false;
        }
        
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            RestoreIPAddresses r = new RestoreIPAddresses();
            for (String s : r.restoreIpAddresses("010010")) {
                System.out.println(s);
            }
        }
    
    }
  • 相关阅读:
    day7
    11.3NOIP模拟赛
    codeforces 880E. Maximum Subsequence(折半搜索+双指针)
    11.2NOIP模拟赛
    bzoj1483: [HNOI2009]梦幻布丁(vector+启发式合并)
    day9
    codeforces 1006 F(折半搜索)
    codeforces 28D(dp)
    P2210 Haywire(A*)
    4800: [Ceoi2015]Ice Hockey World Championship(折半搜索)
  • 原文地址:https://www.cnblogs.com/null00/p/5102153.html
Copyright © 2011-2022 走看看