博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
1到n的所有排列情况
阅读量:4230 次
发布时间:2019-05-26

本文共 1013 字,大约阅读时间需要 3 分钟。

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

具体代码如下:

public class MyTest {    public static List
> 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()); }}
[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

转载地址:http://eajqi.baihongyu.com/

你可能感兴趣的文章
AspectJ Cookbook
查看>>
IntelliJ IDEA in Action
查看>>
HTML Professional Projects
查看>>
Python Cookbook, Second Edition
查看>>
Java Extreme Programming Cookbook
查看>>
XSLT Cookbook
查看>>
Java Programming with Oracle JDBC
查看>>
Hack Proofing Your Network (Second Edition)
查看>>
XML Programming (Core Reference)
查看>>
Visual Studio .NET: The .NET Framework Black Book
查看>>
Best Kept Secrets in .NET
查看>>
SQL: The Complete Reference
查看>>
Wireless Network Hacks & Mods For Dummies
查看>>
Programming INDIGO
查看>>
.NET Development Security Solutions
查看>>
3ds Max 8 Bible
查看>>
Hack Proofing Your Web Applications
查看>>
Hack Proofing ColdFusion
查看>>
Routing TCP/IP, Volume II
查看>>
Unix Systems Programming: Communication, Concurrency and Threads, Second Edition
查看>>