本文主要是介绍Lexicographical Numbers问题及解法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
问题描述:
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.
问题分析:
根据题意,我们可以考虑如下做法,先把1开头的所有值求出,然后再求2,3,...,9开头的值。这个地方我们可能就要用递归来实现我们的算法了。
过程详见代码:
class Solution {
public:vector<int> lexicalOrder(int n) {vector<int> res;bl(res, log10(n), 0, n, 0);return res;}void bl(vector<int>& res, int maxDepth, int depth, int n,int cur){if (depth > maxDepth) return;int i;if (!depth) i = 1;else i = 0;for (; i <= 9; i++){if (cur * 10 + i <= n){res.push_back(cur * 10 + i);bl(res, maxDepth, depth + 1, n, cur * 10 + i);}else return;}}
};
这篇关于Lexicographical Numbers问题及解法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!