问题:
给你一个数字长度,比如是 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