出差期间,看到大学老师教孩子写作业,有这么个问题,突然好奇可不可以用代码实现以下,所以上网搜了下java计算排列组合的知识,觉得受益匪浅。
以下为借鉴别人排列组合的代码写出来的解决方法。
import java.util.ArrayList;
import java.util.List;
public class testadd5 {
static List<int[]> allSorts = new ArrayList<int[]>();
public static void permutation(int[] nums, int start, int end) {
if (start == end) { // 当只要求对数组中一个数字进行全排列时,只要就按该数组输出即可
int[] newNums = new int[nums.length]; // 为新的排列创建一个数组容器
for (int i = 0; i <= end; i++) {
newNums[i] = nums[i];
}
allSorts.add(newNums); // 将新的排列组合存放起来
} else {
for (int i = start; i <= end; i++) {
int temp = nums[start]; // 交换数组第一个元素与后续的元素
nums[start] = nums[i];
nums[i] = temp;
permutation(nums, start + 1, end); // 后续元素递归全排列
nums[i] = nums[start]; // 将交换后的数组还原
nums[start] = temp;
}
}
}
public static int evaluate(int[] num) {
permutation(num, 0, num.length - 1);
int[][] a = new int[allSorts.size()][]; // 你要的二维数组a
allSorts.toArray(a);
int n=0;
int threeend = 0;
int twoend = 0;
// 打印验证
for (int i = 0; i < a.length; i++) {
int[] nums = a[i];
// for (int j = 0; j < nums.length; j++) {
// System.out.print(nums[j]);
// }
// 此循环可以打印出所有结果
int three=nums[0]*100+nums[1]*10+nums[2];
int two=nums[3]*10+nums[4];
int nu=three*two;
if(n<nu) {
n=nu;
threeend=three;
twoend=two;
}
// System.out.println();
}
System.out.println("组合方式个数:"+a.length);
System.out.println("最大值组合方式为:"+threeend+"*"+twoend);
return n;
}
public static void main(String[] args) {
int[] numArray = {1,2,3,4,5};
System.out.println(evaluate(numArray));
}
}
我借鉴的那人巧妙的用了递归,从后向前开始排列所有组合,一开始我没读懂递归来实现的方式,看了打印结果发现,他是一开始直接递归到最底层,然后一步步从后向前来实现。比我一开始死脑筋,一直在想怎么从前向后实现巧妙的很多。
此为借鉴代码出处:https://blog.csdn.net/qq_43493747/article/details/89931179