标签:inpu i++ ssi void oss size ddr rest out
算法描述:
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"]
解题思路:题目要求所有可能的结果,首先想到回溯法。重点有两个,字符串截取和IP地址合法性判断。
vector<string> restoreIpAddresses(string s) { vector<string> results; backtracking(results,"", s, 0,0); return results; } void backtracking(vector<string>& results, string temp, string s, int index, int count){ if(count > 4 ) return; if(count == 4 && index == s.size()){ results.push_back(temp); return; } for(int i=1; i < 4; i++){ if(index+i > s.size()) break; string res = s.substr(index,i); if((res[0]==‘0‘ && res.size() >1) || ( i==3 && stoi(res)>= 256)) continue; backtracking(results, temp+res + (count ==3 ? "" :"."), s, index+i, count+1); } }
LeetCode-93-Restore IP Addresses
标签:inpu i++ ssi void oss size ddr rest out
原文地址:https://www.cnblogs.com/nobodywang/p/10348326.html