我正在尝试编写一个代码,该代码生成一个包含给定int数组的所有可能排列的列表。调用静态类中的非静态方法 - java
我有found online a method(下面的代码中的“nextPermutation”)允许这样做,我试图将它实现为基本代码,但它不起作用。
问题是,当我试图动态地将包含新排列的数组添加到列表中时,已经存储在列表中的所有先前排列都被替换为新排列。
我想这个问题在某种程度上与我的“nextPermutation”是非静态的事实有关,但我不知道我应该怎么做来修复它。
有什么建议吗?
package lang_dist;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class lang_dist {
public boolean nextPermutation(int[] array) {
// Find longest non-increasing suffix
int i = array.length - 1;
while (i > 0 && array[i - 1] >= array[i])
i--;
// Now i is the head index of the suffix
// Are we at the last permutation already?
if (i <= 0)
return false;
// Let array[i - 1] be the pivot
// Find rightmost element that exceeds the pivot
int j = array.length - 1;
while (array[j] <= array[i - 1])
j--;
// Now the value array[j] will become the new pivot
// Assertion: j >= i
// Swap the pivot with j
int temp = array[i - 1];
array[i - 1] = array[j];
array[j] = temp;
// Reverse the suffix
j = array.length - 1;
while (i < j) {
temp = array[i];
array[i] = array[j];
array[j] = temp;
i++;
j--;
}
// Successfully computed the next permutation
return true;
}
public static void main(String[] args)
{
int[] array = {0, 0, 1, 1, 1, 1};
List<int[]> rowList = new ArrayList<int[]>();
List<int[]> results = new ArrayList<int[]>();
lang_dist d=new lang_dist();
while (d.nextPermutation(array)){
System.out.println("Permutation:" + Arrays.toString(array));
results = Arrays.asList(array);
rowList.add(results.get(0));
};
System.out.println("---");
for (int[] row : rowList) {
System.out.println("Row = " + Arrays.toString(row));
}
}
}
有* *静态方法和有*例如*方法。创建一个'lang_dist'('new')的实例并在其上调用你的方法。 –
是的,这就是我试图处理'lang_dist d = new lang_dist(); \t while(d.nextPermutation(array)){...'上面的代码,但它不能解决问题。或者这不是创建实例的正确方法? 对不起,我对java很陌生,我可能会错过一些非常明显的东西.. – yamayama