Skip to content

Commit dc2fd0b

Browse files
authored
Create construct-the-lexicographically-largest-valid-sequence.cpp
1 parent 3e45993 commit dc2fd0b

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
// Time: O(n!)
2+
// Space: O(n)
3+
4+
class Solution {
5+
public:
6+
vector<int> constructDistancedSequence(int n) {
7+
vector<int> result(2 * n - 1);
8+
vector<bool> lookup(n + 1);
9+
backtracking(n, 0, &lookup, &result);
10+
return result;
11+
}
12+
13+
private:
14+
bool backtracking(int n, int i, vector<bool> *lookup, vector<int> *result) {
15+
if (i == size(*result)) {
16+
return true;
17+
}
18+
if ((*result)[i]) {
19+
return backtracking(n, i + 1, lookup, result);
20+
}
21+
for (int x = n; x >= 1; --x) {
22+
int j = (x == 1) ? i : i + x;
23+
if ((*lookup)[x] || j >= size(*result) || (*result)[j]) {
24+
continue;
25+
}
26+
(*result)[i] = (*result)[j] = x, (*lookup)[x] = true;
27+
if (backtracking(n, i + 1, lookup, result)) {
28+
return true;
29+
}
30+
(*result)[i] = (*result)[j] = 0, (*lookup)[x] = false;
31+
32+
}
33+
return false;
34+
}
35+
};

0 commit comments

Comments
 (0)