本文共 1013 字,大约阅读时间需要 3 分钟。
用递归实现,可以这样考虑,n个数的所有情况是 n-1个数的所有排列情况在每种情况中从前往后依次插入第n个数构成的。
具体代码如下:
public class MyTest { public static List[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
> f(int n){ List
> listlist=new ArrayList<>(); if(n==1){ List list=new ArrayList<>(); list.add(1); listlist.add(list); return listlist; }else{ List
> listList2=f(n-1); for(List list:listList2){ for(int i=0;i lst=new ArrayList<>(list); lst.add(i,n); listlist.add(lst); } } return listlist; } } public static void main(String[] args){ List
> list=f(4); for(List lst:list){ System.out.println(lst); } System.out.println(list.size()); }}
转载地址:http://eajqi.baihongyu.com/