Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //https://leetcode.com/problems/cracking-the-safe/description/
- #include <iostream>
- #include <string>
- #include <set>
- using namespace std;
- class Solution {
- private:
- string sequence;
- set<string> passwords;
- int cursor;
- void addPassword(string pswd, int digit_limit) {
- if (passwords.find(pswd) == passwords.end()) {
- sequence += pswd;
- int pswd_len = (int)pswd.length();
- int seq_len = (int)sequence.length();
- if (seq_len > pswd_len) {
- while (cursor < seq_len - pswd_len) {
- string ps = sequence.substr(cursor, pswd_len);
- passwords.insert(ps);
- cursor++;
- }
- }
- }
- }
- void backtrack(string &pswd, int num_digits, int digit_limit){
- if (num_digits == 0) {
- cout << "pswd: " << pswd << endl;
- addPassword(pswd, digit_limit);
- return;
- }
- for (int digit = 0; digit < digit_limit; digit++) {
- pswd += ('0' + digit);
- backtrack(pswd, num_digits - 1, digit_limit);
- pswd.pop_back();
- }
- }
- public:
- Solution() {
- sequence = "";
- cursor = 0;
- }
- string crackSafe(int num_digits, int digit_limit) {
- string pswd = "";
- backtrack(pswd, num_digits, digit_limit);
- return sequence;
- }
- };
- int main(int argc, const char * argv[]) {
- Solution sol;
- cout << sol.crackSafe(2, 2) << endl;
- return 0;
- }
Add Comment
Please, Sign In to add comment