[leetcode]386. Lexicographical Numbers
阿新 • • 發佈:2018-12-24
[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;
};