Leetcode 386. Lexicographical Numbers
Given an integer n
, return 1 to n
in lexicographical order.
n
?
1 <= n <= 50000
.To solve this problem, we can use a depth-first search (DFS) approach. This method allows us to traverse the numbers in lexicographical order naturally.
Here’s the step-by-step strategy:
dfs
that takes the current number and performs the depth-first search.n
, terminate that path.dfs
function with the current number extended by that digit if it forms a valid number within the range of n
.#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> lexicalOrder(int n) {
vector<int> result;
for (int i = 1; i <= 9; i++) {
dfs(i, n, result);
}
return result;
}
private:
void dfs(int current, int n, vector<int>& result) {
if (current > n) return;
result.push_back(current);
for (int i = 0; i <= 9; i++) {
if (current * 10 + i > n) return;
dfs(current * 10 + i, n, result);
}
}
};
int main() {
Solution solution;
int n = 13; // Example usage
vector<int> result = solution.lexicalOrder(n);
for (int num : result) {
cout << num << " ";
}
return 0;
}
The time complexity of this approach is O(n)
because we visit each number from 1 to n
exactly once.
The space complexity is also O(n)
due to the storage used for the result vector and the recursion stack during the DFS traversal.
By implementing this solution, you can efficiently generate the lexicographical numbers from 1 to n
.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?