93. Restore IP Addresses
0. 参考文献
序号 | 文献 |
---|---|
1 | [LeetCode] Restore IP Addresses 复原IP地址 |
2 | 【LeetCode】93. Restore IP Addresses 解题报告(Python & C++) |
1. 题目
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
Example:
Input: "25525511135" Output: ["255.255.11.135", "255.255.111.35"]
2. 思路
本题是判断给到的字符串能够组成的合法IP的数量。对于字符串的问题,如果是匹配或者是子序列的问题,优先考虑DP。但是本题显然不是。求解的办法是使用递归解决。要注意一点就是剪枝,不然Python下会超时。
3. 实现
class Solution(object): def restoreIpAddresses(self, s): """ :type s: str :rtype: List[str] """ if len(s) > 4 * 4: return ret = [] self.restore(ret,"",4,s) return ret def restore(self,ret,tmpstr,k,instr): if len(instr) > k * 4: return if k == 0 and len(instr) ==0 : ret.append(tmpstr) else : for i in range(1,4) : if len(instr) >= i and self.is_vaild(instr[0:i]): if k == 1 : self.restore(ret, tmpstr + instr[0:i], k-1, instr[i:]) else: self.restore(ret, tmpstr + instr[0:i]+".", k-1, instr[i:]) def is_vaild(self,s): if s == "" or len(s) > 3 or ( len(s) > 1 and s[0] == "0" ): return False tmp = int(s) return True if tmp <=255 and tmp >= 0 else False