从长度为N的数组中,选出m个元素,使之和为给定的值

package javase;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;

/**
* 给定最终值,和需要的元素个数,找出符合条件的组合
* @author Mr Liu
* @Time 2018-6-27
*
*/
public class FindExamQuestion2 {

public static void main(String[] args) {



    int[] arr =  getTestResposity();//获得输入的数组

    //int[] arr={-10,45,35,99,10,6,9,20,17,18}; 

    if(arr==null||arr.length==0) {
        System.out.println("输入错误");
    }else {

        Scanner sc = new Scanner(System.in);
        //选择m道题,输入m,需要选出的数组元素的数量
        int m = sc.nextInt();
        //选择需要求得和sum
        int sum = 35;
        calSum(arr,sum,m);
        sc.close();
    }
}
/**
 * 遍历数组
 */
public static void calSum(int[] array,int result,int count) {
     for (int i = 1; i < 1 << array.length; i++)//从1循环到2^N  
        {  
            int sum=0;  
            //定义一个Map,用于存放选出的题目的题号以及分数
            Map<Integer,Integer> examMap = new HashMap<>();
            for (int j = 0; j < array.length; j++)  
            {  
                if ((i & 1 << j) != 0)//用i与2^j进行位与运算,若结果不为0,则表示第j位不为0,从数组中取出第j个数  
                {  
                    sum += array[j];  
                    examMap.put(j,array[j]);  
                }  
            }  
            if (sum == result&&count==examMap.size()) {
                //输出Map
                Set<Entry<Integer,Integer>> entrySet = examMap.entrySet();
                for (Entry<Integer, Integer> entry : entrySet) {
                    System.out.println(entry.getKey()+"\t"+entry.getValue());

                }
                System.out.println("++++++++++++++++++++++++++");
            }
        }  
}
/**
 * 获得题目n的数组
 */
public static int[] getTestResposity() {
    Scanner sc = new Scanner(System.in);
    // n 1-10
    int n = sc.nextInt();
    int[] testResposity = new int[n];
    for (int i=0;i<n;i++) {
        int s = sc.nextInt();
        testResposity[i]=s;
    }
    sc.close();
    return testResposity;
}

}
参考文章:https://blog.csdn.net/MrZZhou/article/details/77860278`

猜你喜欢

转载自blog.csdn.net/weixin_42061676/article/details/80826332