-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathConstruct Smallest Number From DI String.cc
66 lines (54 loc) · 1.79 KB
/
Construct Smallest Number From DI String.cc
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*
Solution by Rahul Surana
***********************************************************
You are given a 0-indexed string pattern of length n consisting of the characters 'I' meaning increasing and 'D' meaning decreasing.
A 0-indexed string num of length n + 1 is created using the following conditions:
num consists of the digits '1' to '9', where each digit is used at most once.
If pattern[i] == 'I', then num[i] < num[i + 1].
If pattern[i] == 'D', then num[i] > num[i + 1].
Return the lexicographically smallest possible string num that meets the conditions.
***********************************************************
*/
class Solution {
public:
unordered_map<int,bool> vv;
long ans, mvv;
void df(int i, string pat, long v){
if(i >= pat.size()) { if(v >= mvv) { ans = min(ans,v); } return; };
// cout << v << "\n";
for(int j = 1; j <= 9; j++){
if(vv[j]) continue;
if(pat[i] == 'I'){
if(v%10 < j ) {
v*=10;
v+=j;
vv[j] = true;
df(i+1,pat,v);
vv[j] = false;
v-=j;
v/=10;
}
}
else{
if(v%10 > j) {
v*=10;
v+=j;
vv[j] = true;
df(i+1,pat,v);
vv[j] = false;
v-=j;
v/=10;
}
}
}
return;
}
string smallestNumber(string pattern) {
mvv = 1;
for(auto x: pattern) mvv*=10;
ans = 99*mvv;
mvv/=10;
for(int i = 1; i <= 9; i++) { vv[i]=true; df(0,pattern,i); vv[i]=false; }
return to_string(ans);
}
};