不断向s中插入'.',然后回溯删除
class Solution { private: vector<string> result; int count = 0; void back_tracking(string& s,int start,int count){ if(count == 3){ if(validate(s,start,s.size()-1)) result.push_back(s); } for(int i = start; i < s.size();i++){ if(validate(s, start, i)){ s.insert(s.begin() + i + 1, '.'); count++; back_tracking(s, i + 2, count); count--; s.erase(s.begin() + i + 1); } } } bool validate(const string& s, int start,int end){ if (start > end) { return false; } if (s[start] == '0' && start != end) { // 0开头的数字不合法 return false; } int num = 0; for (int i = start; i <= end; i++) { if (s[i] > '9' || s[i] < '0') { // 遇到非数字字符不合法 return false; } num = num * 10 + (s[i] - '0'); if (num > 255) { // 如果大于255了不合法 return false; } } return true; } public: vector<string> restoreIpAddresses(string s) { back_tracking(s, 0, 0); return result; } };
1 class Solution { 2 private: 3 vector<vector<int>> result; 4 vector<int> path; 5 void back_tracking(const vector<int>& nums, int start){ 6 result.push_back(path); 7 for(int i = start; i < nums.size(); i++){ 8 path.push_back(nums[i]); 9 back_tracking(nums, i + 1); 10 path.pop_back(); 11 } 12 } 13 public: 14 vector<vector<int>> subsets(vector<int>& nums) { 15 back_tracking(nums, 0); 16 return result; 17 } 18 };
声明一个去重的数组used,先排序,然后回溯
1 class Solution { 2 private: 3 vector<vector<int>> result; 4 vector<int> path; 5 void back_tracking(const vector<int>& nums, int start, vector<bool>& used){ 6 result.push_back(path); 7 for(int i = start; i < nums.size(); i++){ 8 if(i > 0 && nums[i] == nums[i-1] && used[i-1] == false) continue; 9 path.push_back(nums[i]); 10 used[i] = true; 11 back_tracking(nums, i+1, used); 12 used[i] = false; 13 path.pop_back(); 14 } 15 } 16 public: 17 vector<vector<int>> subsetsWithDup(vector<int>& nums) { 18 vector<bool> used(nums.size(),false); 19 sort(nums.begin(), nums.end()); 20 back_tracking(nums, 0, used); 21 return result; 22 } 23 };