输入两个整数n 和m,从数列1,2,3.......n 中随意取几个数,使其和等于m ,要求将其中所有的可能组合列出来.
0,1 背包问题
package search; import java.util.Iterator; import java.util.Stack; public class Zte { private Stack<Integer> stack = new Stack<Integer>(); public void findNM(int sum, int n) { if (n < 0 || sum < 0) { return; } if (sum > 0) { stack.push(n); findNM(sum - n, n - 1); stack.pop(); findNM(sum, n - 1); } else { Iterator<Integer> it = stack.iterator(); while (it.hasNext()) { System.out.print(it.next() + " "); } System.out.println(); } } public static void main(String args[]) { Zte zte = new Zte(); int n = 8; // 1,2,.....n int m = 10; // sum=m; if (n > m) n = m; zte.findNM(m, n); } }