第一个数组的大小为4。 (这将随测试用例而变化)。
让我们说int []包含元素{1, 3, 3, 4}
有什么算法或公式来进行排列并将它们放入int [] []?
例如:将上面的数组置换为3组。
{1, 3, 3, 4}
还要记住,第一个数组的大小并不总是4,但它总是以3为一组。
基本上我需要将int []的排列放入另一个int [] []
答案 0 :(得分:0)
最后,我为任何大小的输入数组实现了permutation
算法。有趣的是,就是这样:
import java.util.Arrays;
public class PermutationCalculator {
public static void main(String[] args) {
final int[] input = {1, 3, 3, 4};
int[][] result = new PermutationCalculator().permutation(input);
// print result
for (int i = 0; i < input.length; i++) {
System.out.println(Arrays.toString(result[i]));
}
}
public int[][] permutation(int[] input) {
int[][] result = new int[input.length][]; // i-th row
for (int i = input.length - 1; i >= 0; i--) {
// negI starts from 0 instead of i which start from end
int negI = input.length - i - 1;
result[negI] = new int[input.length - 1];
// j is row input array index,
// jj is column index (column length = input array -length - 1)
for (int j = 0, jj = 0; jj < input.length; j++, jj++)
if (jj == i) {
j--; // don't need increasing in this case
} else {
result[negI][j] = input[jj];
}
}
return result;
}
}
输出是:
[1, 3, 3]
[1, 3, 4]
[1, 3, 4]
[3, 3, 4]