java编程:给定⼀组正整数数组M,找出M数组中N项和为给定数S。如果有多对N项数字的和都等于 S,则输出N个数的乘积最⼩的哪⼀项,没有则返回空

题目:

编程题:给定⼀组正整数数组M,找出M数组中N项和为给定数S。如果有多对N项数字的和都等于

S,则输出N个数的乘积最⼩的哪⼀项 ,没有则返回空;

程序如下:

测试主程序:

先看下测试示例,一组数据为{ 1, 2, 4, 6, 8, 9, 10, 11, 12, 13, 14, 15, 17, 13, 16 },求3项和为17的最小乘积,结果如下:

程序如下:

java 复制代码
package com.test;

import java.util.ArrayList;
import java.util.Collections;

/**
 * 编程题:给定⼀组正整数数组M,找出M数组中N项和为给定数S。如果有多对N项数字的和都等于
 * S,则输出N个数的乘积最⼩的哪⼀项,没有则返回空;
 */
public class Test{

    public static void main(String[] args) {
        int[] array = { 1, 2, 4, 6, 8, 9, 10, 11, 12, 13, 14, 15, 17, 13, 16 };

        ArrayList productList=new ArrayList();
        combine(array, array.length, 3, new int[3], 3, 17,productList);

        if(productList!=null && productList.size()>0){
            Collections.sort(productList);
            System.out.println("乘积的最小值为:"+productList.get(0));
        }else{
            System.out.println("乘积的最小值为:"+null);
        }
    }

    /**
     *
     * @param a 待处理的正整数数组
     * @param n 数组的长度
     * @param m 要选择的元素的个数
     * @param b 存放结果的数组
     * @param bn 结果数组的个数
     * @param s  需要求得的数组元素之和
     * @param productList 存放所有结果的乘积
     */
    public static void combine(int a[], int n, int m, int b[], int bn, int s,ArrayList productList) {
        for (int i = n; i >= m; i--) {
            b[m - 1] = i - 1;
            if (m > 1) { // 一共要选m个数,故m = 1时才结束递归
                combine(a, i - 1, m - 1, b, bn, s,productList);
            } else {
                if (isSum(a, b, bn, s)) {
                    int product=1;
                    for (int j = bn - 1; j >= 0; j--) {
                        product=product*a[b[j]];
                        System.out.print("数据为:" + a[b[j]]+" ");
                    }
                    System.out.println("乘积为:"+product);
                    productList.add(product);
                }
            }
        }
    }

    /**
     * 判断数组b对应的数组a中的元素之和是否为s
     * @param a 数组a
     * @param b 数组b
     * @param n 数组b的长度
     * @param s 和
     * @return true:数组b对应的数组a中的元素之和是s
     *         false:数组b对应的数组a中的元素之和不是s
     */
    public static boolean isSum(int a[], int b[], int n, int s) {
        int ret = 0;
        for (int i = 0; i < n; i++) {
            ret += a[b[i]];
        }
        return s == ret;
    }
}
相关推荐
Goldn.14 小时前
Java核心技术栈全景解析:从Web开发到AI融合
java· spring boot· 微服务· ai· jvm· maven· hibernate
fie888915 小时前
NSCT(非下采样轮廓波变换)的分解和重建程序
算法
李慕婉学姐15 小时前
【开题答辩过程】以《基于Android的出租车运行监测系统设计与实现》为例,不知道这个选题怎么做的,不知道这个选题怎么开题答辩的可以进来看看
java·后端·vue
m0_7400437315 小时前
SpringBoot05-配置文件-热加载/日志框架slf4j/接口文档工具Swagger/Knife4j
java·spring boot·后端·log4j
编织幻境的妖15 小时前
SQL查询连续登录用户方法详解
java·数据库·sql
晨晖216 小时前
单链表逆转,c语言
c语言·数据结构·算法
未若君雅裁16 小时前
JVM面试篇总结
java·jvm·面试
kk哥889916 小时前
C++ 对象 核心介绍
java·jvm·c++
招风的黑耳16 小时前
我用SpringBoot撸了一个智慧水务监控平台
java·spring boot·后端
xunyan623416 小时前
面向对象(下)-接口的理解
java·开发语言