输入两个整数 n 和 m,从数列1,2,3.......n 中 随意取几个数,

题目:

输入两个整数 n 和 m,从数列1,2,3.......n 中 随意取几个数,
使其和等于 m ,要求将其中所有的可能组合列出来.

代码:

public static int count = 0;
	public static void traverse(int number, int sum, Stack stack) {

		for (int i = number; i > 0; i--) {
			if(sum-i==0){
//				stack.push(i);
				System.out.println("Answer");
				stack.print();
				System.out.println(i);
				count++;
//				stack.pop();
			}else if(sum-i>0){
				stack.push(i);
				traverse(i-1, sum-i,stack);
				stack.pop();
			}
		}
	}

Stack是我实现的一个栈。

猜你喜欢

转载自to-zoe-yang.iteye.com/blog/1173493