返回所有n位整数,每个整数里的值是单调递增的

问题:

给一个值 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);
	}
 
}


转载清注明出处:http://blog.csdn.net/beiyeqingteng

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值