Marvin48

753. Cracking the Safe

Jan 23rd, 2018
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.60 KB | None | 0 0
  1. //https://leetcode.com/problems/cracking-the-safe/description/
  2.  
  3. #include <iostream>
  4. #include <string>
  5. #include <set>
  6.  
  7. using namespace std;
  8.  
  9. class Solution {
  10. private:
  11.     string sequence;
  12.     set<string> passwords;
  13.     int cursor;
  14.    
  15.     void addPassword(string pswd, int digit_limit) {
  16.         if (passwords.find(pswd) == passwords.end()) {
  17.             sequence += pswd;
  18.            
  19.             int pswd_len = (int)pswd.length();
  20.             int seq_len = (int)sequence.length();
  21.             if (seq_len > pswd_len) {
  22.                 while (cursor < seq_len - pswd_len) {
  23.                     string ps = sequence.substr(cursor, pswd_len);
  24.                     passwords.insert(ps);
  25.                     cursor++;
  26.                 }
  27.             }
  28.         }
  29.     }
  30.    
  31.     void backtrack(string &pswd, int num_digits, int digit_limit){
  32.         if (num_digits == 0) {
  33.             cout << "pswd: " << pswd << endl;
  34.             addPassword(pswd, digit_limit);
  35.             return;
  36.         }
  37.        
  38.         for (int digit = 0; digit < digit_limit; digit++) {
  39.             pswd += ('0' + digit);
  40.             backtrack(pswd, num_digits - 1, digit_limit);
  41.             pswd.pop_back();
  42.         }
  43.     }
  44.    
  45. public:
  46.     Solution() {
  47.         sequence = "";
  48.         cursor = 0;
  49.     }
  50.    
  51.     string crackSafe(int num_digits, int digit_limit) {
  52.         string pswd = "";
  53.         backtrack(pswd, num_digits, digit_limit);
  54.        
  55.         return sequence;
  56.     }
  57. };
  58.  
  59. int main(int argc, const char * argv[]) {
  60.     Solution sol;
  61.     cout << sol.crackSafe(2, 2) << endl;
  62.    
  63.     return 0;
  64. }
Add Comment
Please, Sign In to add comment