Location:Home > Turbos product range > Turbo OEM number > 1到n的所有排列情况

1到n的所有排列情况

Time:2018-01-14 05:41Turbochargers information Click:

用递归实现,可以这样考虑,n个数的所有情况是  n-1个数的所有排列情况在每种情况中从前往后依次插入第n个数构成的。

具体代码如下:

public class MyTest { public static List<List<Integer>> f(int n){ List<List<Integer>> listlist=new ArrayList<>(); if(n==1){ List<Integer> list=new ArrayList<>(); list.add(1); listlist.add(list); return listlist; }else{ List<List<Integer>> listList2=f(n-1); for(List<Integer> list:listList2){ for(int i=0;i<n;i++){ List<Integer> lst=new ArrayList<>(list); lst.add(i,n); listlist.add(lst); } } return listlist; } } public static void main(String[] args){ List<List<Integer>> list=f(4); for(List<Integer> lst:list){ System.out.println(lst); } System.out.println(list.size()); } } [4, 3, 2, 1]
[3, 4, 2, 1]
[3, 2, 4, 1]
[3, 2, 1, 4]
[4, 2, 3, 1]
[2, 4, 3, 1]
[2, 3, 4, 1]
[2, 3, 1, 4]
[4, 2, 1, 3]
[2, 4, 1, 3]
[2, 1, 4, 3]
[2, 1, 3, 4]
[4, 3, 1, 2]
[3, 4, 1, 2]
[3, 1, 4, 2]
[3, 1, 2, 4]
[4, 1, 3, 2]
[1, 4, 3, 2]
[1, 3, 4, 2]
[1, 3, 2, 4]
[4, 1, 2, 3]
[1, 4, 2, 3]
[1, 2, 4, 3]
[1, 2, 3, 4]
24

Copyright infringement? Click Here!