如何计算数组元素的所有可能总和

如何解决如何计算数组元素的所有可能总和

我有点拘泥于代码,找不到问题所在。我的任务是在数组中找到最接近x值的总和,并且总和的索引数量不得超过n值。要和的索引可能不是连续的,因此最接近的和可能是索引(0,2,3)而不是(0,1,2)。 我已经写了一些代码,但是n值大于4时不起作用。

在我的代码中,sums(n)的值称为“ towns”,而x值称为“ miles”。

代码来了

  for(int i=0;i<ls.size();i++){
       sum=ls.get(i);
      counterTowns=1;
          if(sum<miles&&counterTowns<towns){
        for(int j=i+1;j<ls.size();j++){
                sum+=ls.get(j);
                counterTowns++;
                if(counterTowns==towns){
                    if(sum<=miles){
                        if(sum>temp){
                            result=sum;
                        }
                        temp=result;
                  }

                    sum=ls.get(i);
                    counterTowns=1;
             if(towns>2){   // I think the problem is in this line
                    j--;
                }
            }
        }
    }
}

更清楚地说,“ ls”是整数的ArrayList。 例如: ArrayList是{50,55,56,57,58}; 城镇= 3,英里= 163,预期产出为163,这是50 + 56 + 57的总和。 当城镇 3,则不能提供正确的输出。 例如,如果ArrayList为{91,74,73,85,73,81,87} 英里= 331,城镇为4,结果是30,而不是331(91 + 74 + 85 + 81)。

我希望我的问题很清楚,如果不能随意问任何问题。 先感谢您。 和平与爱!!!

解决方法

基本上,您需要towns中所有ArrayList元素的组合。
然后,您想要对每种组合中的所有元素求和,并找出和与miles之间的最小差。

我找到了以下代码,用于查找数组中n个元素的所有可能组合。因此,我使用了int而不是ArrayList的数组。请参阅Print all possible combinations of r elements in a given array of size n。我从该网页复制了代码,并对其进行了修改,以解决您的问题。请注意,我将您的示例列表和值用于towns。该代码的说明将显示在其后。

还请注意,代码中的注释来自我复制的原始代码。

public class TownsKms {
    private static int counter;
    private static int kms;
    private static int min = Integer.MAX_VALUE;
    private static int[] minArr;

    /* arr[]  ---> Input Array 
    data[] ---> Temporary array to store current combination 
    start & end ---> Staring and Ending indexes in arr[] 
    index  ---> Current index in data[] 
    r ---> Size of a combination to be printed */
    static void combinationUtil(int arr[],int data[],int start,int end,int index,int r) {
        // Current combination is ready to be printed,print it 
        if (index == r) {
            int sum = 0;
            for (int j=0; j<r; j++) {
                sum += data[j];
            }
            int diff = Math.abs(kms - sum);
            if (diff < min) {
                min = diff;
                System.arraycopy(data,minArr,minArr.length);
            }
            return; 
        } 
  
        // replace index with all possible elements. The condition 
        // "end-i+1 >= r-index" makes sure that including one element 
        // at index will make a combination with remaining elements 
        // at remaining positions 
        for (int i=start; i<=end && end-i+1 >= r-index; i++) {
            data[index] = arr[i]; 
            combinationUtil(arr,data,i+1,end,index+1,r); 
        } 
    } 
  
    // The main function that prints all combinations of size r 
    // in arr[] of size n. This function mainly uses combinationUtil() 
    static void printCombination(int arr[],int n,int r) {
        // A temporary array to store all combination one by one 
        int data[]=new int[r]; 
  
        // Print all combination using temprary array 'data[]' 
        combinationUtil(arr,n-1,r); 
    }

    /**
     * Start here.
     */
    public static void main(String[] args) {
        int arr[] = {91,74,73,85,81,87};
        int towns = 4;
        minArr = new int[towns];
        kms = 331;
        int n = arr.length;
        printCombination(arr,n,towns);
        int sum = 0;
        boolean first = true;
        for (int i = 0; i < minArr.length; i++) {
            if (first) {
                first = false;
            }
            else {
                System.out.print(",");
            }
            sum += minArr[i];
            System.out.print(minArr[i]);
        }
        System.out.println(" = " + sum);
    }
}

我决定不使用更多的参数,而是改用类成员。另外,我将变量miles命名为公里,而不是kms

给定组合中元素的总和与kms的值之差可能为负。您想要最接近零的差异。因此,我计算了绝对差,这就是为什么我调用类abs()的方法Math的原因。

问题中唯一不清楚的是组合的大小是否必须精确地是towns的值,或者可以是从1到towns的任何大小。换句话说,如果towns等于4,您是否要从列表中选择4个元素的所有组合,还是还要检查1、2和3个元素的组合?如果是后者,则需要重复上面的代码,并且每次更改towns的值,即设置towns = 1并运行上面的代码。然后设置towns = 2等。但是请记住重置min

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res