lc 复原IP地址
链接:https://leetcode-cn.com/explore/interview/card/bytedance/242/string/1044/
代码:
#include <string> #include <algorithm> using namespace std; class Solution { public: vector<string> restoreIpAddresses(string s) { string path[5]; int k = 0; int index = 0; vector<string> res; find(s, path, k, index, res); return res; } bool is_valid(string s, int front, int back) { if(back >= s.size()) return false; if(back - front >= 1 && s[front] == '0') return false; string temp = ""; for(int i = front; i <= back; i++) { temp += s[i]; } // cout << temp << endl; int value = stoi(temp); if(value >= 0 && value <= 255) return true; else return false; } void find(string s, string path[], int k, int index, vector<string> & res) { if(index >= s.size()) return; if(k == 3) { // debug string temp = ""; for(int i = index; i <= s.size()-1; i++) { temp += s[i]; } // cout << temp << endl; // if(temp == "135") cout << "++++++++++" << endl; if(s.size() - index > 3) return; if(is_valid(s, index, s.size()-1)) { cout << "====" << endl; string temp = ""; for(int i = index; i <= s.size()-1; i++) { temp += s[i]; } string ss = ""; for(int i = 0; i < 3; i++) { if(i == 0) ss += path[i]; else { ss += "."; ss += path[i]; } } ss += "."; ss += temp; // cout << ss << endl; res.push_back(ss); } return; } for(int i = 0; i <= 2; i++) { if(is_valid(s, index, index+i)) { string temp = ""; for(int j = index; j <= index+i; j++) { temp += s[j]; } path[k] = temp; // cout << "i: " << index << " " << index + i << endl; // cout << "k: " << k << endl; // cout << "path: "; // for(int j = 0; j <= k; j++) { // cout << path[j] << " "; // } // cout << endl; // cout << "------" << endl; if(index+i+1 < s.size() && k < 3) find(s, path, k+1, index+i+1, res); } } return; } };
思路:深搜,不符合条件回溯,记录路径,valid 时候记录方案。
posted on 2020-05-17 23:58 FriskyPuppy 阅读(195) 评论(0) 编辑 收藏 举报