题目描述: 让你从n个数里面找出几个数,加起来之和最大 。且总和要是k的倍数
代码如下:
public static List<Integer> test(int n, int k) {
int[] nums = new int[n];
int index = 0;
Scanner scanner = new Scanner(System.in);
while (n > 0) {
String s = scanner.nextLine();
nums[index] = Integer.parseInt(s);
index++;
n--;
}
Arrays.sort(nums);//排好序
List<Integer> numList = new ArrayList<>();
for (int i : nums) {
numList.add(i);
}
int allSum = getSumByList(numList);
List<Integer> result = new ArrayList<>();
int maxSum = 0;
for (int i = 1; i <= nums.length/2; i++) {
List<List<Integer>> subList = getSubList(nums, i);
for (List<Integer> list : subList) {
int sum = getSumByList(list);
if (sum % k == 0) {
if (sum > maxSum) {
result = list;
maxSum = sum;
}
}
if ((allSum - sum) % 5 == 0) {
if (allSum - sum > maxSum) {
ArrayList<Integer> arrayList = new ArrayList<>(numList);
arrayList.removeAll(list);
result = arrayList;
maxSum=allSum - sum;
}
}
}
}
return result;
}
public static int getSumByList(List<Integer> list) {
int sum = 0;
Iterator<Integer> iterator = list.iterator();
while (iterator.hasNext()) {
Integer next = iterator.next();
sum += next;
}
return sum;
}
//从一个数组里面选n个数出来。把所有可能的n个数的情况都查出来
public static List<List<Integer>> getSubList(int[] nums, int n) {
List<List<Integer>> result = new ArrayList<>();
//处理边界情况
if (n == 1) {
for (int num : nums) {
List<Integer> list = new ArrayList<>();
list.add(num);
result.add(list);
}
return result;
}
int[] restNums = Arrays.copyOfRange(nums, 1, nums.length);
//如果包含当前nums的第一个元素
List<List<Integer>> subList = getSubList(restNums, n - 1);
for (List<Integer> list : subList) {
List<Integer> list1 = new ArrayList<>();
list1.addAll(list);
list1.add(0, nums[0]);
result.add(list1);
}
//如果不包含当前nums的第一个元素
if(restNums.length>=n){
List<List<Integer>> subList1 = getSubList(restNums, n);
result.addAll(subList1);
}
return result;
}