(代码主要是为了备忘) 1.暂时先实现一个数字组合的全部可能性,主要为了记录下来,后期如果有时间就再实现一个全排列
class AllArray{
List<int[]> list = new ArrayList<>();
int[] newArr = new int[4];
public List<int[]> method(int[] arr, int count) {
count++;
if(count == 4) {
return list;
}
for(int i = 0;i < arr.length;i++) {
newArr[count] = arr[i];
List<int[]> list = method(arr,count);
if(isDuplicated(list,newArr)) {
continue;
}
list.add(copyArray(newArr));
}
return list;
}
public int[] copyArray(int[] arr) {
int[] copArr = new int[arr.length];
for(int i = 0;i < copArr.length;i++) {
copArr[i] = arr[i];
}
return copArr;
}
public boolean isDuplicated(List<int[]> list, int[] newArr) {
if(list.size() == 0) {
return false;
}
int[] arr = list.get(list.size() -1 );
int count = 0;
for(int i = 0;i < newArr.length;i++) {
if(arr[i] == newArr[i]) {
count++;
}
}
if(count == 4) {
return true;
}
return false;
}
}
2.实现全排列,代码如下:
class AllArray {
private List<int[]> list = new ArrayList<>();
private int[] newArr = null;
private int[] arr = null;
public AllArray(int[] arr) {
this.arr = arr;
newArr = new int[arr.length];
}
public List<int[]> array(boolean[] newb) {
return method(newb,arr,-1);
}
public List<int[]> method(boolean[] newb, int[] arr, int count) {
count++;
if (count == arr.length) {
return list;
}
for (int i = 0; i < arr.length; i++) {
if (!newb[i]) {
newArr[count] = arr[i];
newb[i] = true;
List<int[]> list = method(newb, arr, count);
newb[i] = false;
if (isDuplicated(list, newArr)) {
continue;
}
list.add(copyArray(newArr));
}
}
return list;
}
private int[] copyArray(int[] arr) {
int[] copArr = new int[arr.length];
for (int i = 0; i < copArr.length; i++) {
copArr[i] = arr[i];
}
return copArr;
}
private boolean isDuplicated(List<int[]> list, int[] newArr) {
if (list.size() == 0) {
return false;
}
int[] arr = list.get(list.size() - 1);
int count = 0;
for (int i = 0; i < newArr.length; i++) {
if (arr[i] == newArr[i]) {
count++;
}
}
if (count == 4) {
return true;
}
return false;
}
}
|