我如何从数组中获取元素,使和等于给定值

时间:2019-06-24 04:22:41

标签: java

我怎么能找到数组中求和给定数字的最小整数。该程序应要求用户输入整数数组(“ Input Array”)和所需的总和(“ Required Sum”)。输出(“输出”)应列出输入数组中累加“所需总和”的最小整数。

在这里,我创建 function sum(),并在从用户 45 读取总和时声明带有一些元素的数组,它为我提供了输出 25,25 ,但是当我输入 59 60 时,输出中没有任何显示

 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]

4 个答案:

答案 0 :(得分:0)

请找到以下我认为最适合您的方案的程序。 考虑到内存和时间方面的考虑,该解决方案可能不是最佳的,您可以根据自己的情况对其进行优化。

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;


public class Subset {

    static public void main (String[] ab)
    {
        int s[] = {10, 0, -1, 20, 25, 30};
        int sum = 45;
        ArrayList<ArrayList<Integer>> lis = subsets(s,sum);
        Iterator<ArrayList<Integer>> t1 = lis.iterator();
        while (t1.hasNext()) {
            List<Integer> t2= t1.next();
            int count = 0;
            Iterator<Integer> t3 = t2.iterator();
            while (t3.hasNext()) {
                count = count+ t3.next();
            }
            if(count ==sum)
                System.out.println(t2);
        }

    }

    public static  ArrayList<ArrayList<Integer>> subsets(int[] S,int sum) {
        if (S == null)
            return null;

        Arrays.sort(S);

        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();

        for (int i = 0; i < S.length; i++) {
            ArrayList<ArrayList<Integer>> temp = new ArrayList<ArrayList<Integer>>();

            //get sets that are already in result
            for (ArrayList<Integer> a : result) {
                temp.add(new ArrayList<Integer>(a));
            }

            //add S[i] to existing sets
            for (ArrayList<Integer> a : temp) {
                a.add(S[i]);
            }

            //add S[i] only as a set
            ArrayList<Integer> single = new ArrayList<Integer>();
            single.add(S[i]);
            temp.add(single);

            result.addAll(temp);
        }

        //add empty set
        result.add(new ArrayList<Integer>());

        return result;
    }
}

希望这会有所帮助。

答案 1 :(得分:0)

使用简单数组尝试此代码 我从用户输入的数组中创建了集合,并打印了所有集合,并且集合的总和等于用户输入的总和。

import java.util.*;
public class Main{


    public static void set(int[] temp,int sum){
     int n=temp.length;

        for (int i = 0; i < (1<<n); i++) 
        {  int sumc=0;
        int count=0;
            System.out.print("{ "); 

            // Print current subset 
            for (int j = 0; j < n; j++) 

                // (1<<j) is a number with jth bit 1 
                // so when we 'and' them with the 
                // subset number we get which numbers 
                // are present in the subset and which 
                // are not 
                if ((i & (1 << j)) > 0) {
                    System.out.print(temp[j] + " "); 
                    sumc=sumc+temp[j];     
                    count++;
                }
                if(sum==sumc){
            System.out.println("}"+" sum :"+sumc +" solution with "+count+" elements"); 
                }else{
                    System.out.println("}");
                }
        } 


    }



    public static void main(String args[]){
        Scanner sc=new Scanner(System.in);
        System.out.println("enter size of array : ");
        int n=sc.nextInt();
        int[] a=new int[n];


        int sum;
        for(int i=0;i<n;i++)
        {
            System.out.print("enter "+i+" element value of array : ");
            a[i]=sc.nextInt();
            System.out.println();
        }
        System.out.println("enter sum : ");
        sum=sc.nextInt();
        set(a,sum);
    }
}

输出:

output of this code with

答案 2 :(得分:0)

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);
    }
}

答案 3 :(得分:0)

import java.util.*;
public class sum2
{
    public static Stack<Integer> find(int A[],int currSum,int index,int sum,int solution[],Stack<Integer> s)
    {
        if(currSum==sum)
        {
            int len=s.size();
            if(len<=s.size() ) 
              { 
                  s.clear();
              }      
            for(int i=0;i<solution.length;i++)
                {
                    if(solution[i]==1) {
                        if(A[i]!=0 )
                        {
                            s.push(A[i]);
                        }
                    }   
                }
            len=s.size();
            return s;   
        }           
        else if(index==A.length)
        {
            return s ;
        }
        else 
        {
            solution[index]=1;
            currSum+=A[index];
            find(A,currSum,index+1,sum,solution,s);
            currSum-=A[index];
            solution[index]=0;
            find(A,currSum,index+1,sum,solution,s);
            return s;   
        }
    }
    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);
        System.out.print("Enter Array size");
        int size=sc.nextInt();
        int A[] =new int[size];
        System.out.println("Enter elements");
        for(int i=0;i<A.length;i++)
        {
            A[i]=sc.nextInt();
        }
        System.out.println("Enter sum");
        int sum=sc.nextInt();
        int solution[]=new int[A.length];
        Stack<Integer> s=new Stack<Integer>();
        Arrays.sort(A);
        find(A,0,0,sum,solution,s);
        System.out.print("Output:" +s); 
    }   
}

花了将近3天