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




























  • 相关阅读:
    3月9号作业
    7、循环之while循环和深浅copy
    6、可变不可变类型和运算符以及流程控制之if判断
    5、垃圾回收机制与用户交互以及运算符
    作业3月5号
    3月4号作业
    4、语法之变量以及基本数据类型
    3、Python介绍
    2、计算机基础详解
    五、流程控制值if...else
  • 原文地址:https://www.cnblogs.com/lux-ace/p/10557016.html
Copyright © 2011-2022 走看看