Maintaining a lexicographical order means that every 10 comes ahead of every 2. One approach is to use recursion. For every number added to list, we first check if its tenfold is in the range, if it is, recursively add its tenfold. Then we increment the number.
public List<integer> lexicalOrder(int n) {
List<integer> rst = new ArrayList<>();
if (n < 1) {
return rst;
}
getList(1, rst, n);
return rst;
}
private void getList(int curr, List rst, int n) {
rst.add(curr);
if (curr * 10 <= n) {
getList(curr * 10, rst, n);
}
if (curr < n && curr % 10 < 9) {
getList(curr + 1, rst, n);
}
}
No comments:
Post a Comment