zoukankan      html  css  js  c++  java
  • 算法笔记_041:寻找和为定值的多个数(Java)

    目录

    1 问题描述

    2 解决方案

     


    1 问题描述

    输入两个整数nsum,要求从数列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的所有组合数为:
    7 9 
    6 10 
    4 5 7 
    3 4 9 
    3 5 8 
    3 6 7 
    2 3 5 6 
    2 3 4 7 
    2 4 10 
    2 5 9 
    2 6 8 
    1 2 6 7 
    1 2 5 8 
    1 2 4 9 
    1 2 3 4 6 
    1 2 3 10 
    1 3 5 7 
    1 3 4 8 
    1 4 5 6 
    1 5 10 
    1 6 9 
    1 7 8 

     

  • 相关阅读:
    Linq 和 Lambda 查询中按照多个值进行分组GroupBy
    enter键触发事件的清除
    3、Python 基础类型 -- List 列表类型
    2、Python 基础类型 -- String 字符串类型
    1、Python 基础类型 -- Number 数字类型
    JMeter 常用网站
    性能测试之基础理论
    JMeter 性能测试实例
    JMeter 服务器监控插件环境配置
    【C++】利用指针实现通过函数改变多个参数的值
  • 原文地址:https://www.cnblogs.com/liuzhen1995/p/6421529.html
Copyright © 2011-2022 走看看