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:
    vector<string>ans;
    vector<int>tempans;
    vector<string> 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();
            }
        }
    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章