zoukankan      html  css  js  c++  java
  • Java实现寻找和为定值的多个数

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

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

    package com.liuzhen.array_2;
    
    public class ManySumN {
        /*
         * 函数功能:以字符串形式返回1~n个数的所有子集,其中0代表不包含其中数字i,1代表 包含其中数字i
         * 此段代码是运用反射格雷码的思想,具体解释详见:算法笔记_019:背包问题(Java)
    */
        public String[] getAllGroup(int n){
            int len = (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;
        }
        /*
         * 参数n:代表有1~n的n个不同整数
         * 函数功能:打印出1~n中所有随机组合的几个数,其相加的和等于sum
         */
        public void printManySumN(int n,int sum){
            System.out.println("1~"+n+"个数中,相加之和等于"+sum+"的所有组合数为:");
            String[] allGroup = getAllGroup(n);
            for(int i = 0;i < allGroup.length;i++){
                char[] temp = allGroup[i].toCharArray();
                int tempSum = 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();
                }
            }
        }
        
        public static void main(String[] args){
            ManySumN test = new ManySumN();
            test.printManySumN(10, 16);
        }
    }
    

    运行结果:

    1~10个数中,相加之和等于16的所有组合数为:
    9 
    10 
    5 7 
    4 9 
    5 8 
    6 7 
    3 5 6 
    3 4 7 
    4 10 
    5 9 
    6 8 
    2 6 7 
    2 5 8 
    2 4 9 
    2 3 4 6 
    2 3 10 
    3 5 7 
    3 4 8 
    4 5 6 
    5 10 
    6 9 
    7 8
    
  • 相关阅读:
    Golang 入门~~基础知识
    Redis命令总结
    CI框架在辅助函数中使用配置文件中的变量
    前后端分离--三层
    前后端分层--两层
    JavaScript中的cookie
    JavaScript的类、对象、原型、继承、引用
    Qt编写自定义控件46-树状导航栏
    Qt编写自定义控件45-柱状标尺控件
    Qt编写自定义控件44-天气仪表盘
  • 原文地址:https://www.cnblogs.com/a1439775520/p/12948039.html
Copyright © 2011-2022 走看看