- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 70 lines of C++ from the credited upstream file permutations-iv.cpp.
- The implementation visibly relies on sequence storage.
- 6 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution {6public:7 vector<int> permute(int n, long long k) {8 vector<int> result;9 vector<int64_t> cnt(n + 1, 1);10 for (int i = 1; i + 1 < size(cnt); ++i) {11 cnt[i + 1] = min(cnt[i] * ((i + 2) / 2), static_cast<int64_t>(k));12 }13 vector<bool> lookup(n);14 for (int i = 0; i < n; ++i) {15 int j = 0;16 for (; j < n; ++j) {17 if (!(!lookup[j] && ((i == 0 && n % 2 == 0) || ((j + 1) % 2 == (!empty(result) ? (result.back() % 2) ^ 1 : 1))))) {18 continue;19 }20 if (k <= cnt[n - 1 - i]) {21 break;22 }23 k -= cnt[n - 1 - i];24 }25 if (j == n) {26 return {};27 }28 lookup[j] = true;29 result.emplace_back(j + 1);30 }31 return result;32 }33};34 35363738class Solution2 {39public:40 vector<int> permute(int n, long long k) {41 typedef __int128 int128_t;42 43 vector<int> result;44 vector<int128_t> fact((((n - 1) + 1) / 2) + 1, 1);45 for (int i = 0; i + 1 < size(fact); ++i) {46 fact[i + 1] = min(fact[i] * (i + 1), static_cast<int128_t>(k));47 }48 vector<bool> lookup(n);49 for (int i = 0; i < n; ++i) {50 const auto cnt = fact[(n - 1 - i) / 2] * fact[((n - 1 - i) + 1) / 2];51 int j = 0;52 for (; j < n; ++j) {53 if (!(!lookup[j] && ((i == 0 && n % 2 == 0) || ((j + 1) % 2 == (!empty(result) ? (result.back() % 2) ^ 1 : 1))))) {54 continue;55 }56 if (k <= cnt) {57 break;58 }59 k -= cnt;60 }61 if (j == n) {62 return {};63 }64 lookup[j] = true;65 result.emplace_back(j + 1);66 }67 return result;68 }69};70