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




























  • 相关阅读:
    前端工程师需要的技能
    微信小程序
    前端问题总结
    vue面试题
    vue 双数据绑定原理
    路由配置5步
    chrome浏览器自动填充失效问题
    spring 登录提示 Bad credentials
    spring 项目tomcat 8.0.2 发布报错:Could not initialize class org.hibernate.validator.engine.ConfigurationImpl
    spring tiles界面为空白
  • 原文地址:https://www.cnblogs.com/lux-ace/p/10557016.html
Copyright © 2011-2022 走看看