[leetcode]386. Lexicographical Numbers
Analysis
normal day—— [每天刷题并不难0.0]
Given an integer n, return 1 - n in lexicographical order.
For example, given 13, return: [1,10,11,12,13,2,3,4,5,6,7,8,9].
Please optimize your algorithm to use less time and space. The input size may be as large as 5,000,000.
Implement
试图直接暴力解决,意料之中的MLE T.T
class Solution {
public:
vector<int> lexicalOrder(int n) {
vector<string> str;
for(int i=1; i<=n; i++)
str.push_back(to_string(i));
sort(str.begin(), str.end());
vector<int> res;
for(auto s:str)
res.push_back(stoi(s));
return res;
}
};
看了讨论区的解答,发现这道题的关键其实是根据当前数字找到下一个数字。
class Solution {
public:
vector<int> lexicalOrder(int n) {
vector<int> res;
int tmp = 1;
for(int i=1; i<=n; i++){
res.push_back(tmp);
if(tmp*10 <= n)
tmp *= 10;
else if(tmp%10 != 9 && tmp+1 <= n)
tmp += 1;
else{
while(tmp%10 == 9 || tmp == n)
tmp /= 10;
tmp += 1;
}
}
return res;
}
};
用DFS解决好像跟简单易懂一些,可以把结果看成一系列的树:
class Solution {
public:
vector<int> lexicalOrder(int n) {
for(int i=1; i<10; i++)
dfs(i, n);
return res;
}
void dfs(int cur, int n){
if(cur > n)
return ;
res.push_back(cur);
for(int i=0; i<10; i++){
if(cur*10+i > n)
return ;
dfs(cur*10+i, n);
}
}
private:
vector<int> res;
};