【问题标题】:how can i get elements from array which makes sum equals to given value如何从数组中获取元素,使总和等于给定值
【发布时间】:2020-09-07 21:04:05
【问题描述】:

如何在数组中找到对给定数字求和的最小整数。程序应要求用户输入整数数组(“Input Array”)和所需的总和(“Required Sum”)。输出(“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]

【问题讨论】:

  • 方法从根本上是不正确的,因为您正在将数字添加到 temp,但是会有两条路径,其中一条您将选择当前数字,而另一条则不会。寻找子集子问题,这是与此相关的一个链接。 algorithms.tutorialhorizon.com/…

标签: java


【解决方案1】:
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);
    }
}

【讨论】:

    【解决方案2】:

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

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

    希望这对您有所帮助。

    【讨论】:

      【解决方案3】:

      用简单的数组试试这个代码 我从用户输入的数组创建了集合并打印所有这些集合,并且总和等于用户输入的总和我正在显示解决方案和元素计数,以便更好地理解。

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

      输出:

      【讨论】:

        【解决方案4】:
        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 天

        【讨论】:

          猜你喜欢
          • 2020-06-04
          • 2014-05-26
          • 2019-03-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-06-02
          相关资源
          最近更新 更多