Skip to content

Commit d0fa5a1

Browse files
authored
Create 1718. Construct the Lexicographically Largest Valid Sequence
1 parent 53a386e commit d0fa5a1

File tree

1 file changed

+36
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)