https://leetcode.com/problems/restore-ip-addresses/

1. Use recursion:

  1. //4 ms 6.7 MB
  2. class Solution {
  3. public:
  4. vector<string> restoreIpAddresses(string s) {
  5. vector<string> result;
  6. //pickSub(result, s, "", 4);
  7. pickSub(&result, s, "", 4);
  8. return result;
  9. }
  10. //void pickSub(vector<string>& result, string s, string curr, int rest){
  11. void pickSub(vector<string>* result, string s, string curr, int rest){
  12. if(s.length() > rest*3)
  13. return;
  14. if(rest!=0 && rest!=4)
  15. curr += ".";
  16. if(rest == 0){
  17. //result.push_back(curr);
  18. result->push_back(curr);
  19. return;
  20. }
  21. string s_l;
  22. string s_r;
  23. for(int i=1; i<=3; i++){
  24. if(s.length()>=i){
  25. s_l = s.substr(0, i);
  26. if(s.length()>=i+1)
  27. s_r = s.substr(i);
  28. else
  29. s_r = "";
  30. if((stoi(s_l) <= 255)
  31. && ((stoi(s_l) > 0 && (s_l[0] != '0'))
  32. || (stoi(s_l) == 0) && (s_l == "0"))){
  33. pickSub(result, s_r, curr + s_l, rest-1);
  34. }
  35. }
  36. }
  37. }
  38. };