java求1至19这些自然数数中,所有相加为20的组合

来源:互联网 发布:java Renameto什么意思 编辑:程序博客网 时间:2024/05/02 00:50

使用Stack来完成:

代码如下:

package ca.map;import java.util.Stack;public class Sum1_19eq20 {    //算法: 求1至19这些自然数数中,所有相加为20的组合    public static void main(String[] args) {        combinateDataOfRange(1, 19, 20);    }    public static void combinateDataOfRange(int min,int max,int target){        combinateData(0, min, max, target, new Stack<Integer>());    }    public static void combinateData(int sum,int min,int max,int target,Stack<Integer> stack){        for(int i = stack.isEmpty() ? min : (Integer)stack.lastElement() + 1;i < max;++i){            int tempSum = sum + i;            stack.push(i);            if(tempSum == target){                System.out.println(stack+"="+target);            }else{                combinateData(tempSum, min, max, target, stack);            }            stack.pop();        }    }}

输出为:

[1, 2, 3, 4, 10]=20
[1, 2, 3, 5, 9]=20
[1, 2, 3, 6, 8]=20
[1, 2, 3, 14]=20
[1, 2, 4, 5, 8]=20
[1, 2, 4, 6, 7]=20
[1, 2, 4, 13]=20
[1, 2, 5, 12]=20
[1, 2, 6, 11]=20
[1, 2, 7, 10]=20
[1, 2, 8, 9]=20
[1, 2, 17]=20
[1, 3, 4, 5, 7]=20
[1, 3, 4, 12]=20
[1, 3, 5, 11]=20
[1, 3, 6, 10]=20
[1, 3, 7, 9]=20
[1, 3, 16]=20
[1, 4, 5, 10]=20
[1, 4, 6, 9]=20
[1, 4, 7, 8]=20
[1, 4, 15]=20
[1, 5, 6, 8]=20
[1, 5, 14]=20
[1, 6, 13]=20
[1, 7, 12]=20
[1, 8, 11]=20
[1, 9, 10]=20
[2, 3, 4, 5, 6]=20
[2, 3, 4, 11]=20
[2, 3, 5, 10]=20
[2, 3, 6, 9]=20
[2, 3, 7, 8]=20
[2, 3, 15]=20
[2, 4, 5, 9]=20
[2, 4, 6, 8]=20
[2, 4, 14]=20
[2, 5, 6, 7]=20
[2, 5, 13]=20
[2, 6, 12]=20
[2, 7, 11]=20
[2, 8, 10]=20
[2, 18]=20
[3, 4, 5, 8]=20
[3, 4, 6, 7]=20
[3, 4, 13]=20
[3, 5, 12]=20
[3, 6, 11]=20
[3, 7, 10]=20
[3, 8, 9]=20
[3, 17]=20
[4, 5, 11]=20
[4, 6, 10]=20
[4, 7, 9]=20
[4, 16]=20
[5, 6, 9]=20
[5, 7, 8]=20
[5, 15]=20
[6, 14]=20
[7, 13]=20
[8, 12]=20
[9, 11]=20

0 0