leetcode--IP 주소 복원--중점,dfs

3315 단어 LeetCode
https://leetcode.com/problems/restore-ip-addresses/
all possible solutions 를 구 하 는 것 은 dfs backtracking 일 것 입 니 다.
레 퍼 런 스http://www.cnblogs.com/zuoyuan/p/3768112.html http://blog.csdn.net/linhuanmars/article/details/24683699
my code:
class Solution(object):

    def isValid(self, s):
        if s == '' or len(s) > 3:
            return False

        if len(s) > 1 and s[0] == '0':
            return False

        if 0<= int(s) <=255:
            return True    
        return False

    def dfs(self, s, slice_num, subres, res):
        if slice_num == 0 and len(s) == 0:
            res.append(subres[1:])
            return
        #elif len(s) == 0:#      ,            
         # return
        else:
            for i in xrange(1, 4):#          3
                if self.isValid(s[:i]) and i <= len(s):#     i<= len(s)    ,        ,      s[i:]
                    self.dfs(s[i:], slice_num - 1, subres + '.' + s[:i], res)


    def restoreIpAddresses(self, s):
        """ :type s: str :rtype: List[str] """
        if len(s) > 12: return []
        res = []
        self.dfs(s, 4, '',res)
        return res

좋은 웹페이지 즐겨찾기