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'
, thennum[i] < num[i + 1]
. - If
pattern[i] == 'D'
, thennum[i] > num[i + 1]
.
Return the lexicographically smallest possible string num
that meets the conditions.
Construct Smallest Number From DI String LeetCode Contest
Example 1:
Input: pattern = "IIIDIDDD" Output: "123549876" Explanation: At indices 0, 1, 2, and 4 we must have that num[i] < num[i+1]. At indices 3, 5, 6, and 7 we must have that num[i] > num[i+1]. Some possible values of num are "245639871", "135749862", and "123849765". It can be proven that "123549876" is the smallest possible num that meets the conditions. Note that "123414321" is not possible because the digit '1' is used more than once.
Example 2:
Input: pattern = "DDD" Output: "4321" Explanation: Some possible values of num are "9876", "7321", and "8742". It can be proven that "4321" is the smallest possible num that meets the conditions.
Constraints:
1 <= pattern.length <= 8
pattern
consists of only the letters'I'
and'D'
.
Solution
class Solution {
public:
string smallestNumber(string pattern) {
string cur = "";
unordered_set<int> used;
return backtracking(pattern, cur, used, -1);
}
string backtracking(string &pattern, string &cur, unordered_set<int> &used, int i) {
if (i == pattern.length()) return cur;
string res;
for (int k = 1; k <= 9; ++k) {
if (used.count(k)) continue;
char chr = char(k + '0');
cur += chr;
used.insert(k);
if (i == -1) {
res = backtracking(pattern, cur, used, i + 1);
} else {
char prev = cur[cur.size() - 2];
if ((pattern[i] == 'I' && chr > prev) || (pattern[i] == 'D' && chr < prev))
res = backtracking(pattern, cur, used, i + 1);
}
used.erase(k);
cur.pop_back();
if (!res.empty()) return res;
}
return "";
}
};
class Solution {
String pat, res = "";
boolean[] vis = new boolean[10];
public String smallestNumber(String pattern) {
this.pat = pattern;
for(int i=1; i<10; i++){
if(helper(i, 0, i+"")) break;
vis[i] = false;
}
return res;
}
boolean helper(int last, int idx, String s){
if(idx==pat.length()){
res = s; return true;
}
vis[last] = true;
boolean flag = pat.charAt(idx)=='I';
for(int i = flag?last+1:1; (flag&&i<=9) || (!flag&&i<=last-1); i++){
if(vis[i]) continue;
if(helper(i, idx+1, s+i)) return true;
vis[i] = false;
}
return false;
}
}
class Solution:
def smallestNumber(self, pattern: str) -> str:
ans = [1]
for ch in pattern:
if ch == 'I':
m = ans[-1]+1
while m in ans: m += 1
ans.append(m)
else:
ans.append(ans[-1])
for i in range(len(ans)-1, 0, -1):
if ans[i-1] == ans[i]: ans[i-1] += 1
return ''.join(map(str, ans))
Happy Learning – If you require any further information, feel free to contact me.