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




























  • 相关阅读:
    nginx 配置详解
    ngnix 负载均衡
    nginx 安装搭建与配置介绍
    11.15java实习生面试总结
    笔试题:编写一个用户注册接口
    java第一次笔试+面试总结
    《啊哈算法》读后总结(下)
    java常见排序算法
    Tomcat安装及配置教程
    算法题:购买n个苹果,苹果6个一袋或者8个一袋,若想袋数最少,如何购买?
  • 原文地址:https://www.cnblogs.com/lux-ace/p/10557016.html
Copyright © 2011-2022 走看看