my dfs c++ code


  • 0
    Q

    class Solution {
    public:
    vector <string> fin;
    vector<string> restoreIpAddresses(string s) {
    int len = s.size();
    string ans;
    solve(s, 3, len, ans, 0);
    return fin;
    }
    private:
    void solve(string s, int step, int len, string ans, int start) {
    if ((len > 3 * (step + 1)) || (len < (step + 1))) { return; }
    if (step == 0&&!topzero(s.substr(start))&& stoi(s.substr(start)) < 256) {
    ans = ans + s.substr(start);
    fin.push_back(ans);

    		ans.clear();
    		return;
    	}
    	
    	
    	for (int i = 1; i <= 3; i++) {
    		if (!topzero(s.substr(start, i))&&stoi(s.substr(start, i)) >= 0 && stoi(s.substr(start, i)) < 256) {
    			string temp = ans;
    			ans = ans + s.substr(start, i) + ".";
    			solve(s, step - 1, len - i, ans,start+i);
    			ans = temp;
    		}
    		
    	}
    
    }
    bool topzero(string s) {
    	if (s[0] == '0'&&s.size() > 1) return true;
    	return false;
    }
    

    };


Log in to reply
 

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