Why my code would produce runtime error?


  • 0
    D

    The idea is to use backtracking, but it's not correct. Can anyone help with identifying what the problem is ?

    Thanks.

    class Solution {
    public:
    	void dfs(vector<vector<int>> &res, int n, string s, vector<int> &t, int idx)
    	{
    		if (idx == n)
    		{
    			res.push_back(t);
    			return;
    		}
    		else
    		{
    
    				for (int j = idx+1; j <= idx+3; j++)
    				{
    					string tmp = s.substr(idx, j-idx);
    					std::string::size_type sz;   
    					int tmpint = stoi(tmp, &sz);
    					if (tmpint == 0)
    					{
    						if (j-idx>1)
    							break;
    					}
    					if (tmpint >= 0 && tmpint<256)
    					{
    						t.push_back(j);
    						dfs(res, n, s, t, j);
    						t.pop_back();
    					}
    				}
    
    			
    		}
    	}
    	vector<string> restoreIpAddresses(string s) {
    		vector<vector<int>> res;
    		vector<string> results;
    		int len = s.length();
    		vector<int> t;
    
    		dfs(res, len, s, t, 0);
    
    		string ns;
    		//change from res to results
    		for (int i = 0; i<res.size(); i++)
    		{
    			ns = s;
    			for (int j = 0; j<res[i].size()-1; j++)
    			{
    				ns.insert(res[i][j]+j, 1, '.');
    			}
    			results.push_back(ns);
    		}
    		return results;
    	}
    };

  • 0
    M

    Why don't you compile it on your local machine? Compiler could give you detailed information for free. And, by simply skimming over your dfs(), it neglects too many cases. It won't be right anyway.


Log in to reply
 

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