问一个问题
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
*
* @author Mr Zhang
* 全排列数组的全排列
* 为什么要new ArrayList<Integer>(list)
*/
public class Perm {
public static void main(String[] args) {
List<ArrayList<Integer>> perm=new ArrayList<>();
ArrayList<Integer> list=new ArrayList<>();
list.add(1);
list.add(3);
list.add(5);
calperm(perm, list, 0);
System.out.println(perm);
}
public static void calperm(List<ArrayList<Integer>> perm, ArrayList<Integer> list, int n) {
if (n == list.size()) {
perm.add(new ArrayList<Integer>(list));//此处为什么要新建一个list,而如果直接用list出不了结果?
} else {
for (int i = n; i < list.size(); i++) {
Collections.swap(list, i, n);
System.out.println(list);
calperm(perm, list, n + 1);
Collections.swap(list, i, n);
}
}
}
}
import java.util.Collections;
import java.util.List;
/**
*
* @author Mr Zhang
* 全排列数组的全排列
* 为什么要new ArrayList<Integer>(list)
*/
public class Perm {
public static void main(String[] args) {
List<ArrayList<Integer>> perm=new ArrayList<>();
ArrayList<Integer> list=new ArrayList<>();
list.add(1);
list.add(3);
list.add(5);
calperm(perm, list, 0);
System.out.println(perm);
}
public static void calperm(List<ArrayList<Integer>> perm, ArrayList<Integer> list, int n) {
if (n == list.size()) {
perm.add(new ArrayList<Integer>(list));//此处为什么要新建一个list,而如果直接用list出不了结果?
} else {
for (int i = n; i < list.size(); i++) {
Collections.swap(list, i, n);
System.out.println(list);
calperm(perm, list, n + 1);
Collections.swap(list, i, n);
}
}
}
}