Simple Python DFS method.


  • 0
    O

    A simple dfs method. The results ans is aggregated from the terminal nodes.

    class Solution(object):
        def restoreIpAddresses(self, s):
            """
            :type s: str
            :rtype: List[str]
            """
            ans = []
            def G(S,record):
                """record:List of strings"""
                if len(record)==4:
                    if len(S)==0:
                        ans.append('.'.join(record))
                    else:return
                if len(S)==0:return            
                for i in range(3): 
                    if len(S)<i+1:break
                    if int(S[0:i+1])<256:
                        G(S[i+1:],record+[S[0:i+1]])                
                    if i==0 and S[0]=='0':break
            G(s,[])
            return ans
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.