接到一个客户的需求,类似这样的:从数据集中挑出10个和为435的数,要求用JAVA实现,只输出一组结果代码如下:
import java.util.ArrayList;
import java.util.List;
public class Main {
public static List<Integer> findCombination(int[] nums, int i, int m) {
List<Integer> result = new ArrayList<>();
backtrack(nums, i, m, 0, new ArrayList<>(), result);
return result;
}
private static void backtrack(int[] nums, int i, int m, int start, List<Integer> tempList, List<Integer> result) {
if (tempList.size() == i) {
if(sum(tempList) == m) result.addAll(tempList);
return;
}
for (int j = start; j < nums.length && result.size()==0; j++) {
tempList.add(nums[j]);
backtrack(nums, i, m, j + 1, tempList, result);
tempList.remove(tempList.size() - 1);
}
}
private static int sum(List<Integer> list) {
int sum = 0;
for (int num : list) {
sum += num;
}
return sum;
}
public static void main(String[] args) {
int[] dataset = {26, 83, 13, 79, 51, 61, 8, 89, 69, 52, 46, 57, 21, 54, 55, 97, 82, 2, 8, 21, 10, 82, 50, 97, 81, 40, 59, 24, 61, 36, 76, 43, 40, 92, 49, 30, 61, 27, 93, 89, 34, 35, 1, 40, 70, 42, 25, 1, 99, 53, 1, 90, 70, 84, 79, 40, 80, 14, 67, 25, 70, 44, 59, 71, 89, 81, 29, 22, 1, 82, 38, 80, 59, 41, 86, 61, 88, 32, 82, 33};
int i = 10;
int m = 435;
List<Integer> result = findCombination(dataset, i, m);
System.out.println(result);
}
}
输出:
[26, 83, 13, 79, 51, 61, 8, 89, 24, 1] |