[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 };
posted @ 2012-11-14 16:00  chkkch  阅读(3112)  评论(1编辑  收藏  举报