[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 public:

 3     bool isVail(string s) {

 4         if (s.length() != 1 && s[0] == '0') 

 5             return false;

 6         int n = s[0] - '0';

 7         for (int i = 1; i < s.size(); ++i) {

 8             n *= 10;

 9             n += (s[i] - '0');

10         }

11         return n <= 255;

12     }

13     

14     void findNext(vector<string> &res, string &s, string substr, int cnt, int idx) {

15         if (cnt < 4 && cnt > 0) 

16             substr.push_back('.');

17         if (cnt == 4 && idx == s.length()) {

18             res.push_back(substr);

19             return;

20         } else if (cnt == 4 && idx != s.length()) {

21             return;

22         }

23         

24         string digit;

25         for (int len = 1; len <= 3 && idx + len <= s.length(); ++len) {

26             digit = s.substr(idx, len);

27             if (isVail(digit)) {

28                 findNext(res, s, substr + digit, cnt + 1, idx + len);

29             }

30         }

31     }

32     

33     vector<string> restoreIpAddresses(string s) {

34         vector<string> res;

35         findNext(res, s, "", 0, 0);

36         return res;

37     }

38 };

 

你可能感兴趣的:(LeetCode)