zoukankan      html  css  js  c++  java
  • 递归和回溯_leetcode93-经典的回溯题

    class Solution(object):
    def restoreIpAddresses(self, s):
    """
    :type s: str
    :rtype: List[str]
    """
    self.res = []

    self.findCombination(s,"",0)
    return self.res


    def findCombination(self,s,ans,count):


    if not s:
    return


    if count == 3:

    curNum = int(s)
    if curNum >= 0 and curNum < 256:
    ans = ans + "." + s
    print ans
    self.res.append(ans)
    return



    length = len(s)
    for i in range(1,length+1):


    strNum = s[0:i]
    curNum = int(strNum)

    if curNum >= 0 and curNum < 256:

    if count == 0:

    oldAns = ans
    ans = ans + strNum
    self.findCombination(s[i:],ans,count+1)
    ans = oldAns


    else:
    oldAns = ans
    ans = ans + "." + strNum
    self.findCombination(s[i:],ans,count+1)
    ans = oldAns

    else:
    break





    class Solution2(object):
    def restoreIpAddresses(self, s):
    """
    :type s: str
    :rtype: List[str]
    """
    self.res = []

    self.findCombination(s,"",0)
    return self.res


    def findCombination(self,s,ans,count):


    if not s or len(s) > 12:
    return


    if count == 3:



    curNum = int(s)

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

    if curNum >= 0 and curNum < 256:
    ans = ans + "." + s
    print ans
    self.res.append(ans)
    return



    length = len(s)
    for i in range(1,length+1):


    strNum = s[0:i]
    curNum = int(strNum)

    if len(strNum) > 1 and int(strNum[0]) == 0:
    return

    if curNum >= 0 and curNum < 256:

    if count == 0:

    oldAns = ans
    ans = ans + strNum
    self.findCombination(s[i:],ans,count+1)
    ans = oldAns


    else:
    oldAns = ans
    ans = ans + "." + strNum
    self.findCombination(s[i:],ans,count+1)
    ans = oldAns

    else:
    break



    s = Solution2()

    ip = "1111"

    s.restoreIpAddresses(ip)

    print s.res




























  • 相关阅读:
    PHP返回随机颜色
    SQL Server 系统表介绍:sys.dm_exec_requests
    ORA27300 ORA27301 ORA27302 ORA27157
    Linux的subversion安装配置
    批处理计算n天前\后的日期
    Linux下vsftp配置
    RedHat Linux 5企业版开启VNCSERVER远程桌面功能
    WAS 6.1命令行(静默)安装
    五板斧封杀Windows操作系统默认共享(图)
    Select Top在不同数据库中的使用用法:
  • 原文地址:https://www.cnblogs.com/lux-ace/p/10557016.html
Copyright © 2011-2022 走看看