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;
    }
}
相关推荐
.生产的驴4 分钟前
SpringBoot 封装统一API返回格式对象 标准化开发 请求封装 统一格式处理
java·数据库·spring boot·后端·spring·eclipse·maven
猿周LV12 分钟前
JMeter 安装及使用 [软件测试工具]
java·测试工具·jmeter·单元测试·压力测试
知来者逆14 分钟前
计算机视觉——速度与精度的完美结合的实时目标检测算法RF-DETR详解
图像处理·人工智能·深度学习·算法·目标检测·计算机视觉·rf-detr
晨集14 分钟前
Uni-App 多端电子合同开源项目介绍
java·spring boot·uni-app·电子合同
时间之城16 分钟前
笔记:记一次使用EasyExcel重写convertToExcelData方法无法读取@ExcelDictFormat注解的问题(已解决)
java·spring boot·笔记·spring·excel
阿让啊18 分钟前
C语言中操作字节的某一位
c语言·开发语言·数据结构·单片机·算法
এ᭄画画的北北19 分钟前
力扣-160.相交链表
算法·leetcode·链表
椰羊~王小美24 分钟前
LeetCode -- Flora -- edit 2025-04-25
java·开发语言
凯酱31 分钟前
MyBatis-Plus分页插件的使用
java·tomcat·mybatis
程序员总部42 分钟前
如何在IDEA中高效使用Test注解进行单元测试?
java·单元测试·intellij-idea