gpt4 book ai didi

java - 我如何从数组中获取使总和等于给定值的元素

转载 作者:行者123 更新时间:2023-12-02 09:45:00 26 4
gpt4 key购买 nike

如何找到数组中给定数字之和的最小整数数。程序应要求用户输入整数数组(“输入数组”)和所需的总和(“所需总和”)。输出(“Output”)应列出输入数组中总结“Required Sum”的最小整数数。

这里我创建了函数 sum() 并声明了包含一些元素的数组,当从用户45读取总和时,它给了我输出25,25> 但是当我输入 5960 时,输出中没有显示任何内容

 public static void sum()
{


int arr[]={10,0,-1,20,25,30};
Scanner in=new Scanner(System.in);
int sum=in.nextInt();

int[] sub = new int[arr.length];
int temp = 0;
for (int i = 0; i < arr.length; i++)
{
for (int j = i, col = 0; j < arr.length; j++, col++)
{
//add the value of input array one by one
temp += arr[j];
sub[col] = arr[j];
//if addition is equal to sum then print it
if (temp == sum)
{
int total = 0;
for (int k = 0; k < sub.length; k++)
{
total += sub[k];
System.out.println(sub[k]);

//if total and sum are equal then leave the print
if (total == sum)
{
System.out.println();
break;
}
}
}
//if temp is greater than sum are equal then clear the sub array, set temp value and leave the loop for next
if (temp > sum)
{
temp = 0;
break;
}
}
}

}

输出示例:

输入数组: [10, 0, -1, 20, 25, 30]

所需金额: 45输出: [20, 25]

所需金额: 59输出: [10, -1, 20, 30]

所需金额: 60输出: [10, 20, 30]

最佳答案

import java.util.*;
public class Runner
{

public static void find(int[] A, int currSum, int index, int sum,int[] solution)
{
if (currSum == sum)
{

System.out.print("Output: [");
for (int i = 0; i < solution.length; i++)
{
if (solution[i] == 1)
{
if(A[i]!=0)
{
System.out.print(" " + A[i]);
}
}
}
System.out.print(" ]\n");

}
else if (index == A.length)
{
return;
}
else
{
solution[index] = 1;// select the element
currSum += A[index];
find(A, currSum, index + 1, sum, solution);
currSum -= A[index];
solution[index] = 0;// do not select the element
find(A, currSum, index + 1, sum, solution);
}
return;
}


public static void main(String args[])
{
Scanner in =new Scanner(System.in);
System.out.println("How many integer you have to insert: ");
int n=in.nextInt();
int []A=new int[n];
System.out.println("\nEnter elements in Array:\n ");
for(int i=0;i<A.length;i++)
{
A[i]=in.nextInt();
}
System.out.println("\nEnter required sum: ");
int sum=in.nextInt();
int[] solution = new int[A.length];
find(A, 0, 0, sum, solution);
}
}

关于java - 我如何从数组中获取使总和等于给定值的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56729818/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com