Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 50a2a48

Browse files
Create Construct the Lexicographically Largest Valid Sequence
1 parent 1b1aad0 commit 50a2a48

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
想法:利用 Recursive Backtracking 的技巧,找過所有的可能序列,並輸出最大者。
2+
由於題目要求要回傳字典序最大者;所以我們從數字大填到小,只要一找到解即可停止遞迴並回傳
3+
4+
Time Complexity : O(n!) for there are n! possible sequence
5+
(or you can think as the first digit has n candidates , second digit has n - 1 ... to the last digit , total complexity is
6+
n * (n - 1) * (n - 2) ... * 1 = O(n!) )
7+
Space Complexity : O(n! for the recursion (recursion depth = O(n))
8+
9+
class Solution {
10+
public:
11+
vector<int> ans , appear ;
12+
bool construct(int n , int index) {
13+
if (index == 2 * n - 1)
14+
return true ;
15+
if ( ans[index] != 0 )
16+
return construct(n , index + 1) ;
17+
18+
for(int num = n ; num > 0 ; num--) {
19+
if ( appear[num] == 0 && ans[index] == 0
20+
&& (num == 1 || (index + num < 2 * n - 1 && ans[index + num] == 0)) ) {
21+
appear[num] = 1 ;
22+
if (num == 1)
23+
ans[index] = 1 ;
24+
else
25+
ans[index] = ans[index + num] = num ;
26+
if ( construct(n , index + 1) )
27+
return true ;
28+
29+
appear[num] = 0;
30+
if (num == 1)
31+
ans[index] = 0 ;
32+
else
33+
ans[index] = ans[index + num] = 0;
34+
}
35+
}
36+
return false ;
37+
}
38+
vector<int> constructDistancedSequence(int n) {
39+
ans.resize(2 * n - 1) ;
40+
appear.resize(n + 1) ;
41+
construct(n , 0) ;
42+
return ans ;
43+
}
44+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /