-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.ts
52 lines (48 loc) · 1.23 KB
/
Solution.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
function smallestNumber(pattern: string): string {
const n = pattern.length;
const res = new Array(n + 1).fill('');
const vis = new Array(n + 1).fill(false);
const dfs = (i: number, num: number) => {
if (i === n) {
return;
}
if (vis[num]) {
vis[num] = false;
if (pattern[i] === 'I') {
dfs(i - 1, num - 1);
} else {
dfs(i - 1, num + 1);
}
return;
}
vis[num] = true;
res[i] = num;
if (pattern[i] === 'I') {
for (let j = res[i] + 1; j <= n + 1; j++) {
if (!vis[j]) {
dfs(i + 1, j);
return;
}
}
vis[num] = false;
dfs(i, num - 1);
} else {
for (let j = res[i] - 1; j > 0; j--) {
if (!vis[j]) {
dfs(i + 1, j);
return;
}
}
vis[num] = false;
dfs(i, num + 1);
}
};
dfs(0, 1);
for (let i = 1; i <= n + 1; i++) {
if (!vis[i]) {
res[n] = i;
break;
}
}
return res.join('');
}