zoukankan      html  css  js  c++  java
  • [LeetCode] 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)

    DFS搜索所有的可能解,同时判断解的合法性。

     1 class Solution {
     2 private:
     3     vector<string> ret;
     4     int pos[4];
     5 public:
     6     bool check(string &s, int beg, int end)
     7     {
     8         string ip(s, beg, end - beg + 1);
     9         if (ip.size() == 1)
    10             return "0" <= ip && ip <= "9";
    11         else if (ip.size() == 2)
    12             return "10" <= ip && ip <= "99";
    13         else if (ip.size() == 3)
    14             return "100" <= ip && ip <= "255";
    15         else
    16             return false;
    17     }
    18     
    19     void dfs(int dep, int maxDep, string &s, int start)
    20     {
    21         if (dep == maxDep)
    22         {
    23             if (start == s.size())
    24             {
    25                 int beg = 0;
    26                 string addr;
    27                 for(int i = 0; i < maxDep; i++)
    28                 {
    29                     string ip(s, beg, pos[i] - beg + 1);
    30                     beg = pos[i] + 1;
    31                     addr += i == 0 ? ip : "." + ip;
    32                 }
    33                 ret.push_back(addr);    
    34             }
    35             return;
    36         }
    37         
    38         for(int i = start; i < s.size(); i++)
    39             if (check(s, start, i))
    40             {
    41                 pos[dep] = i;
    42                 dfs(dep + 1, maxDep, s, i + 1);               
    43             }
    44     }
    45     
    46     vector<string> restoreIpAddresses(string s) {
    47         // Start typing your C/C++ solution below
    48         // DO NOT write int main() function
    49         ret.clear();
    50         dfs(0, 4, s, 0);
    51         return ret;
    52     }
    53 };
  • 相关阅读:
    leetcode 63 简单题
    leetcode 712
    500 问的数学基础
    转载一份kaggle的特征工程:经纬度、特征构造、转化率
    散度
    在线学习在CTR上应用的综述
    广告的计费方式
    矩阵2范数与向量2范数的关系
    text_CNN笔记
    F1
  • 原文地址:https://www.cnblogs.com/chkkch/p/2770072.html
Copyright © 2011-2022 走看看