问题:
给一个值 n , 返回所有 n 位整数,每个整数里的值是单调递增的。 比如,n = 3,那么长度为3的整数有 123, 124, 125, 134,。。。等。122, 222,这些是不符合条件的。
分析:
首先,第一个数从1开始,最多到 9 结束,第二个数从 "第一个数 + 1" 开始,最多到 9 结束,第三个数从 “第二个数 + 1”开始,最多到9结束,以此类推。每次到10以后,就不在继续下去,而且,如果整数的长度为 n 的时候,我们就可以把它输出。这里我们用stack 来保存每一位数,通过调用 push 和 pop方法,我们可以非常方便的对数字进行处理。
public class NIncreasingDigits {
/**
* @author beiyeqingteng
* @param cl : current length
* @param n: required length
* @param digit: 1 - 9
* @param stack: stack is used to save the result
*/
public void nIncreasingDigits(int cl, int n, int digit, Stack<Integer> stack) {
//satisfy the condition, output the result
if (cl == n) {
System.out.println(stack.toString());
return ;
}
// violate the condition
if (digit > 9) return;
// use the current digit, length + 1
stack.push(digit);
nIncreasingDigits(cl + 1, n, digit+1, stack);
// doesn't use the current digit, the length remains the same
stack.pop();
nIncreasingDigits(cl, n, digit+1, stack);
}
public static void main(String[] args) {
Stack<Integer> stack = new Stack<Integer>();
NIncreasingDigits nd = new NIncreasingDigits();
// n = 3
nd.nIncreasingDigits(0, 3, 1, stack);
}
}