LeetCode OJ:Restore IP Addresses(存储IP地址)

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,但是要点是注意什么才是真的ip地址,代码如下:

 1 class Solution {
 2 public:
 3     vector<string> restoreIpAddresses(string s) {
 4         if (s.size() > 12) return ret;
 5         dfs(s, 0, 0);
 6         return ret;
 7     }
 8     
 9     bool check(string &s)
10     {
11         if (s.size() == 1)
12             return "0" <= s && s <= "9";
13         else if (s.size() == 2)
14             return "10" <= s && s <= "99";
15         else if (s.size() == 3)
16             return "100" <= s && s <= "255";
17         else
18             return false;
19     }
20 
21     void dfs(const string & s, int start, int nth)
22     {
23         if (nth == 4 && start != s.size())
24             return;
25         else if (nth == 4 && start == s.size()){
26             string tmp = "";
27             for (int i = 0; i < 3; ++i){
28                 tmp += tmpRes[i];
29                 tmp += ".";
30             }
31             tmp += tmpRes[3];    //为了凑格式
32             ret.push_back(tmp);
33         }
34         else
35             for (int i = 1; i < 4; ++i){
36                 if(start + i <= s.size()){
37                     string tmp = s.substr(start, i);
38                     if(check(tmp)){
39                         tmpRes.push_back(tmp);
40                         dfs(s, start + i, nth + 1);
41                         tmpRes.pop_back();
42                     }
43                 }
44             }
45     }
46 
47 private:
48     vector<string> tmpRes;
49     vector<string> ret;
50 };

写的有点乱了 ,见谅见谅

转载于:https://www.cnblogs.com/-wang-cheng/p/4953672.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值