题目

给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式。
有效的 IP 地址正好由四个整数(每个整数位于 0 到 255 之间组成),整数之间用 '.'分隔。

示例:
输入: "25525511135"
输出: ["255.255.11.135", "255.255.111.35"]

方案(回溯)

  1. class Solution:
  2. def restoreIpAddresses(self, s: str) -> List[str]:
  3. if len(s) <= 3:
  4. return []
  5. # 回溯
  6. # 我们现在有4个 . 每个数字后可以选择放或者不放,然后放完之后判断是否合法即可
  7. # 注: "0.0.0.0" 合法, 但是 "0.00.1.0" 不合法
  8. ret = []
  9. def helper(index, count, prefix):
  10. '''
  11. index: 当前处理到 s 的 index
  12. count: 已放置 . 的个数
  13. prefix: 已经放置的结果, eg. prefix = "255.255.11."
  14. '''
  15. if index >= len(s):
  16. return
  17. if count == 3:
  18. if s[index] == "0" and len(s) - index > 1: # 结尾为 0x, 0xx
  19. return
  20. if int(s[index:]) > 255:
  21. return
  22. ret.append(prefix + s[index:])
  23. count += 1
  24. if s[index] == "0":
  25. return helper(index+1, count, prefix+s[index:index+1]+".")
  26. if len(s) - index >= 1:
  27. helper(index+1, count, prefix+s[index:index+1]+".")
  28. if len(s) - index >= 2:
  29. helper(index+2, count, prefix+s[index:index+2]+".")
  30. if len(s) - index >= 3 and int(s[index:index+3]) <= 255:
  31. helper(index+3, count, prefix+s[index:index+3]+".")
  32. helper(0, 0, "")
  33. return ret

原文

https://leetcode-cn.com/explore/interview/card/2020-top-interview-questions/292/simulation/1309/