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




























  • 相关阅读:
    Linux系统调用
    Kubernetes 中强化tab 功能
    Docker镜像构建之案例分享
    网络基础之名词介绍
    网络基础协议之UDP(下篇)
    网络基础协议之UDP(上篇)
    内核升级
    尼恩 Java高并发三部曲 [官方]
    CDN图解(秒懂
    DNS图解(秒懂
  • 原文地址:https://www.cnblogs.com/lux-ace/p/10557016.html
Copyright © 2011-2022 走看看