题目来源
https://leetcode.com/problems/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)
题意分析
Input:一串数字
Output:可能的ip
Conditions:符合0~255
题目思路
用dfs,要注意考虑0.0.0.0的情况,不考虑00.00.00.00这样多个0的
AC代码(Python)
1 class Solution(object): 2 def restoreIpAddresses(self, s): 3 """ 4 :type s: str 5 :rtype: List[str] 6 """ 7 def dfs(s, sub, ips, ip): 8 if sub == 4: 9 if s == "": 10 ips.append(ip[1:]) 11 return 12 for i in range(1,4): 13 if i <= len(s): 14 if int(s[:i]) <= 255: 15 dfs(s[i:], sub + 1, ips, ip+"."+s[:i]) 16 if s[0] == "0": 17 break 18 ips = [] 19 dfs(s, 0, ips, "") 20 return ips