找出长度为n的所有数字,里面相邻数字不能一样 [No.53]

问题:

给你一个数字长度,比如是 n ,那么打印出所有长度为 n 的数字,但是相邻数字不能一样。假如n = 3,那么121是可以的,112是不行的。

分析:

首先,该数字的第一个位置可以是1-9任意值,然后第二个位置可以是1-9任意值,但是不能和前面一个值相等。对于第三个位置,道理是一样的,所以,这里我们需要用到递归。对于每一个位置,我们需要遍历所有与前面位置不同的值。

public class NDigit {
	
	/**
	 * @author beiyeqingteng
	 * @param length : current digit's length
	 * @param n: required length
	 * @param digit: 1 - 9
	 * @param stack: stack is used to save the result
	 */
	public static void ndigit(int length, int n, int digit, Stack<Integer> stack) {
		
		//satisfy the condition, output the result
		if (length == n) {
			System.out.println(stack.toString());
        	return ;
		}
		if (length > n) return;
		//digit for the next position
		//enumerate all different cases
		for (int i = 1; i <= 9; i++ ) {
			if (i != digit) {
				stack.push(i);
				ndigit(length + 1, n, i, stack);
				stack.pop();
			}			
		}
	}
	
	public static void main(String[] args) {
		int n = 3;
		for (int i = 1; i <= 9; i++ ) {
			Stack<Integer> stack = new Stack<Integer>();
			stack.push(i);
			ndigit(1, n, i, stack);
		}
	}
}

扩展:打印所有长度为n的数字,里面数字是单调递增的。比如,长度为4的数字 1234是单调递增的, 1368是单调递增的,1431不是单调递增的, 1131也不是单调递增的。

解答请参考:http://blog.csdn.net/beiyeqingteng/article/details/7289211


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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值