题目描述

给定一个只包含数字的字符串,用以表示一个 IP 地址,返回所有可能从 s 获得的 有效 IP 地址 。你可以按任何顺序返回答案。有效 IP 地址 正好由四个整数(每个整数位于 0 到 255 之间组成,且不能含有前导 0),整数之间用 ‘.’ 分隔。例如:”0.1.2.201” 和 “192.168.1.1” 是 有效 IP 地址,但是 “0.011.255.245”、”192.168.1.312” 和 “192.168@1.1” 是 无效 IP 地址。

示例1

  1. 输入:s = "25525511135"
  2. 输出:["255.255.11.135","255.255.111.35"]

示例2

  1. 输入:s = "0000"
  2. 输出:["0.0.0.0"]

示例3

  1. 输入:s = "010010"
  2. 输出:["0.10.0.10","0.100.1.0"]

解题思路

IP地址最短只有1位,最长有3位,一位的话允许有0,因此我们还是可以采用DFS的方法进行分割,(需要注意0这个特殊数字)

  1. class Solution {
  2. public:
  3. vector<string> res;
  4. void func(string curr, string &s, int idx, int count) {
  5. if (count > 4)
  6. return;
  7. if (idx == s.length() && count == 4) {
  8. curr.pop_back();
  9. res.push_back(curr);
  10. return;
  11. }
  12. if (s[idx] == '0') {
  13. func(curr+"0.", s, idx+1, count+1);
  14. }
  15. else {
  16. for (int i=1; i<=3; i++) {
  17. if (idx+i > s.length())
  18. continue;
  19. string sub_str = s.substr(idx, i);
  20. if (stoi(sub_str) < 256)
  21. func(curr+sub_str+".", s, idx+i, count+1);
  22. }
  23. }
  24. }
  25. vector<string> restoreIpAddresses(string s) {
  26. func("", s, 0, 0);
  27. return res;
  28. }
  29. };