寻找和为定值的n个数

来源:互联网 发布:基础设施即服务 云计算 编辑:程序博客网 时间:2024/05/29 07:01

寻找和为定值的N个数

题目:

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

思路:

上述问题是典型的背包问题的应用,即先找出n个数的所有组合,再在这些组合中寻找组合数相加之和等于sum的组合,并依次输出这些组合中的数。

实现:

public class ManySumN {

      public static void main(String[] args) {

             new ManySumN().printManySumN(5, 4);

      }    

      public String[] getAllGroup(int n) {

             intlen = (int) Math.pow(2, n);

             String[] result = new String[len];

             if(n == 1) {

                    result[0]= "0";

                    result[1]= "1";

                    return result;

             }

             String[] temp = getAllGroup(n - 1);

             for(int i = 0; i < temp.length; i++) {

                    result[i]= "0" + temp[i];

                    result[len- 1 - i] = "1" + temp[i];

             }

             return result;

      }  

      public void printManySumN(int n, int sum){

             String[] allGroup = getAllGroup(n);

             for(int i = 0; i < allGroup.length; i++) {

                    char[]temp = allGroup[i].toCharArray();

                    inttempSum = 0;

                    for(int j = 0; j < temp.length; j++) {

                           if(temp[j]=='1'){

                                  tempSum+=(j+1);

                           }

                    }

                    if(tempSum== sum){

                           for(int j=0;j<temp.length;j++){

                                  if(temp[j]=='1'){

                                         System.out.print((j+1)+"");

                                  }

                           }

                           System.out.println();

                    }

             }

      }

}

原创粉丝点击