LeetCode93 Restore IP Addresses

题目:

Given a string containing only digits, restore it by returning all possible valid IP address combinations. (Medium)

For example:
Given "25525511135",

return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)

分析:

使用回溯法即可。helper函数用来处理DFS过程,isValid判断一个子串是否符合IP地址一个点分十进制的一块。

注意在isValid中要除去类似00,01这种0打头的情况。

代码:

 1 class Solution {
 2 private:
 3     vector<string> result;
 4     bool isValid(const string& s) {
 5         if (s[0] == '0' && s.size() > 1) {  // for case like "00.122.122.122"
 6             return false;
 7         }
 8         int num = stoi(s);
 9         if (num >= 0 && num <= 255) {
10             return true;
11         }
12         return false;
13     }   
14     void helper(const string& s, string curS, int start, int step) {
15         if (step == 4) {
16             if (start != s.size()) {
17                 return;
18             }
19             curS.pop_back();
20             result.push_back(curS);
21             return;
22         }
23         for (int i = 1; i <= 3; ++i) {
24             if (start + i <= s.size()) {
25                 string tempS = s.substr(start, i);
26                 if (isValid(tempS)) {
27                     string newS = curS + tempS;
28                     newS.push_back('.');
29                     helper(s, newS, start + i, step + 1);
30                 }                
31             }
32         }
33     }
34 public:
35     vector<string> restoreIpAddresses(string s) {
36         string curS;
37         helper(s, curS, 0, 0);
38         return result;
39     }
40 };

 

posted @ 2016-10-24 21:01  wangxiaobao1114  阅读(148)  评论(0编辑  收藏  举报