LeetCode93 Restore IP Addresses 还原IP地址

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"]

题源:here;完整实现:here

思路:

递归法,但是要注意去除重复的情况,代码如下:

void recurse(string s, vector<int> solution, vector<string> &result){
	if (solution.size() == 4){
		if (s.size()) return;
		string str;
		for (int i = 0; i < 3; i++){
			str += to_string(solution[i]) + ".";
		}
		str += to_string(solution[3]);
		result.push_back(str);
		return;
	}
		
	for (int i = 0; i < 3 && i < s.size(); i++){
		if (i>0 && s[0] == '0') continue;
		int value = stoi(s.substr(0, i + 1));
		if (value >= 0 && value <= 255){
			string tempS = s; vector<int> tempSolution = solution;
			tempS.erase(0, i + 1); tempSolution.push_back(value);
			recurse(tempS, tempSolution, result);
		}
	}
}

vector<string> restoreIpAddresses(string s) {
	vector<string> result;
	recurse(s, {}, result);

	return result;
}

纪念贴图:



猜你喜欢

转载自blog.csdn.net/m0_37518259/article/details/81045435
今日推荐