LeetCode93. Restore IP Addresses(C++)

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

Example:

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

解题思路:回溯剪枝,从题目本身来看,将一串数字字符串分为4份,要保证每一份转换成的数字在0-255之间。其中需要留意,不可以将001(类似格式)作为单独一份,所以当遍历到的数字为0,只能单独为一份。

class Solution {
public:
    vectorans;
    vectortempans;
    vector restoreIpAddresses(string s) {
        dfs(s, 0, 0);
        return ans;
    }
    void dfs(string s, int cur, int cnt){
        if(cur == s.length() && cnt == 4){
            string res = to_string(tempans[0]);
            for(int i = 1; i < tempans.size(); ++ i)
                res += '.' + to_string(tempans[i]);
            ans.push_back(res);
            return;
        }
        if(cur == s.length() || cnt == 4)
            return;
        string temp;
        if(s[cur] == '0'){
            tempans.push_back(0);
            dfs(s, cur+1, cnt+1);
            tempans.pop_back();
        }
        else{
            for(int len = 1; len <= 3; ++ len){
                if(cur + len > s.length())
                    break;
                int num = stoi(s.substr(cur, len));
                if(num > 255)
                    break;
                tempans.push_back(num);
                dfs(s, cur+len, cnt+1);
                tempans.pop_back();
            }
        }
    }
};

 

你可能感兴趣的:(Leetcode)