Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

93. Restore IP Addresses #20

Open
LLancelot opened this issue Jul 31, 2020 · 0 comments
Open

93. Restore IP Addresses #20

LLancelot opened this issue Jul 31, 2020 · 0 comments
Labels
Amazon DFS dfs questions

Comments

@LLancelot
Copy link
Owner

LLancelot commented Jul 31, 2020

https://leetcode.com/problems/restore-ip-addresses/

Given a string containing only digits, restore it by returning all possible valid IP address combinations.

A valid IP address consists of exactly four integers (each integer is between 0 and 255) separated by single points.

Example:

Input: "25525511135"
Output: ["255.255.11.135", "255.255.111.35"]

class Solution(object):
    def restoreIpAddresses(self, s):
        
        def dfs(res, s, curr, field):
            if field == 4 and s == "":
                res.append(curr[1:])
            elif field == 4 or s == "":
                return 
            else:
                # add 1 digit into curr, then dfs
                dfs(res, s[1:], curr + "." + s[0:1], field + 1)
                
                # add 2 digits into curr, then dfs
                if s[0] != "0" and len(s) > 1:
                    dfs(res, s[2:], curr + "." + s[0:2], field + 1)
                    
                    # add 3 digits into curr, then dfs
                    if len(s) > 2 and int(s[0:3]) <= 255:
                        dfs(res, s[3:], curr + "." + s[0:3], field + 1)
         
        res=[]
        if not s or len(s) > 12:
            return res
        
        dfs(res, s, "", 0)
        return res
@LLancelot LLancelot added DFS dfs questions Amazon labels Jul 31, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Amazon DFS dfs questions
Projects
None yet
Development

No branches or pull requests

1 participant