Created
October 27, 2019 04:03
-
-
Save goldsail/c884ae2e0ffaf60b54f0e8ad9f6b194b to your computer and use it in GitHub Desktop.
LeetCode Weekly Contest 160, Problem 2
This file contains 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: | |
vector<int> circularPermutation(int n, int start) { | |
stack<int> stk; // search stack (open set). Use (-1) to represent a traceback | |
vector<int> currVec; // current state of partial permutation | |
unordered_set<int> currSet; // records integers in currVec | |
stk.push(start); | |
while (!stk.empty()) { | |
int curr = stk.top(); // pop the current value | |
stk.pop(); | |
if (curr < 0) { // trace back mark | |
currSet.erase(currVec.back()); | |
currVec.pop_back(); | |
} | |
currVec.push_back(curr); // append current value to the permutation | |
currSet.insert(curr); | |
// | |
if (currVec.size() == (1 << n)) { // permutation complete | |
int x = currVec.back() ^ start; | |
for (int i = 0; i < n; i++) if (x == (1 << i)) return currVec; | |
currSet.erase(currVec.back()); // trace back if not valid | |
currVec.pop_back(); | |
} | |
// | |
stk.push(-1); // put traceback mark | |
for (int i = 0; i < n; i++) { | |
int x = currVec.back() ^ (1 << i); // push next possible values into open set | |
if (currSet.find(x) == currSet.end()) { | |
stk.push(x); | |
} | |
} | |
} | |
return currVec; | |
} | |
}; |
This file contains 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: | |
vector<int> circularPermutation(int n, int start) { | |
vector<int> currVec; // current state of partial permutation | |
unordered_set<int> currSet; // records integers in currVec | |
currVec.push_back(start); | |
currSet.insert(start); | |
solve(n, start, currVec, currSet); // returns true immediately after any final state is reached | |
return currVec; | |
} | |
private: | |
static bool solve(int n, int start, vector<int>& currStk, unordered_set<int>& currSet) { | |
if (currStk.size() == (1 << n)) { // permutation complete (length reaches 2^n) | |
int x = currStk.back() ^ start; | |
for (int i = 0; i < n; i++) if (x == (1 << i)) return true; | |
return false; | |
} | |
for (int i = 0; i < n; i++) { | |
int x = currStk.back() ^ (1 << i); // next possible value | |
if (currSet.find(x) == currSet.end()) { | |
currStk.push_back(x); | |
currSet.insert(x); | |
if (solve(n, start, currStk, currSet)) { | |
return true; | |
} | |
currStk.pop_back(); | |
currSet.erase(x); | |
} | |
} | |
return false; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment