大数问题
/**
* 剑指 Offer 17. 打印从1到最大的n位数
* https://leetcode.cn/problems/da-yin-cong-1dao-zui-da-de-nwei-shu-lcof/
*
* 思路:回溯思想
* 考虑大数问题(用字符串或数组表示大数)
* */
public class Solution1 {
private List<String> nums;
boolean skipZero = false;
public int[] printNumbers(int n) {
nums = new ArrayList<>((int)Math.pow(10, n) - 1);
print(n, 0, "");
return toArray(nums);
}
private void print(int n, int len, String num) {
if (len == n) {
if (skipZero == false) {
skipZero = true;
} else {
nums.add(num);
}
return;
}
for (int i = 0; i <= 9; i++) {
print(n, len + 1, num + i);
}
}
private int[] toArray(List<String> nums) {
int[] array = new int[nums.size()];
int index = 0;
for (String num : nums) {
array[index++] = Integer.parseInt(num);
}
return array;
}
}
不考虑大数问题
/**
* 不考虑大数问题
* */
public class Solution2 {
public int[] printNumbers(int n) {
// 计算最大值
int max = 1;
for (int i = 0; i < n; i++) {
max *= 10;
}
// 打印 1 到最大 n 位数
int[] nums = new int[max - 1];
for (int i = 1; i < max; i++) {
nums[i - 1] = i;
}
return nums;
}
public static void main(String[] args) {
System.out.println(Arrays.toString(new Solution2().printNumbers(3)));
}
}