Skip to content

Commit b80cc29

Browse files
authored
Create 1718-construct-the-lexicographically-largest-valid-sequence.js
1 parent 1716e25 commit b80cc29

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* @param {number} n
3+
* @return {number[]}
4+
*/
5+
const constructDistancedSequence = function(n) {
6+
const ans = Array(2 * n - 1).fill(0)
7+
const used = Array(n + 1).fill(0)
8+
dfs(ans, 0)
9+
return ans
10+
11+
function dfs(ans, i) {
12+
if(i === ans.length) return true
13+
if(ans[i]) return dfs(ans, i + 1)
14+
for(let j = used.length - 1; j > 0; j--) {
15+
if(used[j]) continue
16+
if(j !== 1 && (i + j >= ans.length || ans[i + j])) continue
17+
used[j] = 1
18+
ans[i] = j
19+
if(j !== 1) ans[i + j] = j
20+
if(dfs(ans, i + 1)) return true
21+
ans[i] = 0
22+
if(j !== 1) ans[i + j] = 0
23+
used[j] = 0
24+
}
25+
return false
26+
}
27+
};

0 commit comments

Comments
 (0)