Created
March 18, 2020 14:54
-
-
Save jakab922/ff87fcbf7dca441aa35023bbc220223b to your computer and use it in GitHub Desktop.
Solution of https://leetcode.com/problems/cracking-the-safe/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
void extend(forward_list<int>::iterator curr, forward_list<int>& route, vector<bool>& was, const int& k, const int& top) { | |
if(!was[*curr]) was[*curr] = true; | |
int neigh; | |
bool changed = true; | |
while(changed) { | |
changed = false; | |
for(int i = 0; i < k; i++) { | |
neigh = (*curr * 10) % top + i; | |
if(was[neigh]) continue; | |
was[neigh] = true; | |
route.insert_after(curr, neigh); | |
curr++; | |
changed = true; | |
break; | |
} | |
} | |
} | |
string crackSafe(int n, int k) { | |
if(k == 1) { | |
stringstream ss; | |
ss << setw(n) << setfill('0') << 0; | |
return ss.str(); | |
} | |
int top = 1; | |
for(int i = 0; i < n; i++) top *= 10; | |
vector<bool> was(10000, false); | |
forward_list<int> route{0}; | |
was[0] = true; | |
for(auto it = route.begin(); it != route.end(); it++) extend(it, route, was, k, top); | |
stringstream ss; | |
for(const auto it : route) { | |
if(it == 0) ss << setw(n) << setfill('0') << 0 << setw(1); | |
else ss << it % 10; | |
} | |
return ss.str(); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment