386: Lexicographical-Numbers
Medium
table of contents
They be recycling daily questions already??!??!? (this was the
daily question on 21/09/2024
)
This question is just a simple recursion problem.
You can see that in the example provided with n = 13
we
get:
[1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9]
as the lexicographical order.
In it, it hints that the recursion equation should be, for any given
i
, we should have a function that iterates through
all the possible digits in the one
s column.
Example:
- for
i = 1
, we have1
to9
- for
i = 130
, we have130
to139
- for
i = 40
, we have40
to49
Then, during this recursive function, while we iterate
through all the possible digits in the one
s
column.
code
class Solution {
public:
void addLexicographicalSmallest(vector<int>& ans, int current, int n) {
for (int i = current; i <= min(current + 9, n); ++i) {
.push_back(i);
ansif ((i * 10) <= n) {
(ans, i*10, n);
addLexicographicalSmallest}
}
}
<int> lexicalOrder(int n) {
vector<int> ans;
vectorfor (int i = 1; i <= min(9, n); ++i) {
.push_back(i);
ansif ((i * 10) <= n) {
(ans, i*10, n);
addLexicographicalSmallest}
}
return ans;
}
};