1~n的全排列--阅文集团2018校招笔试题

题目大意:给定整数n,求出1~n的全排列

示例

输入:n=3

输出:[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]

 1 import java.util.Scanner;
 2 import java.util.ArrayList;
 3 
 4 public class Main{
 5   private void func(ArrayList<Integer> nArray, ArrayList<ArrayList<Integer>> results, ArrayList<Integer> oneResult) {
 6     int nArraySize = nArray.size();
 7     if(nArraySize == 0) {
 8       results.add(new ArrayList<Integer>(oneResult)); // 要新建一个类加入到结果集中,不然最终结果集中所有结果都一样(因为是同一个ArrayList)      
 9       return;
10     }
11     int tmp = 0;
12     for(int i=0; i<nArraySize; i++) {
13       tmp = nArray.get(i);
14       nArray.remove(i);
15       oneResult.add(tmp);
16       func(nArray, results, oneResult);
17       nArray.add(i, tmp);
18       oneResult.remove(oneResult.size()-1);
19     }
20     
21   }
22   
23   public static void main(String[] args) {
24     Main mainClass = new Main();
25     Scanner in = new Scanner(System.in);
26     while(in.hasNext()) {
27       String input = in.next();
28       int n = Integer.parseInt(input.split("=")[1]);
29       ArrayList<Integer> nArray = new ArrayList<Integer>();
30       for(int i=1; i<=n; i++) {
31         nArray.add(i);
32       }
33       
34       ArrayList<ArrayList<Integer>> results = new ArrayList<ArrayList<Integer>>();
35       mainClass.func(nArray, results, new ArrayList<Integer>());
36       
37       /**
38        * 构造输出格式
39        */
40       StringBuilder stringBuilder = new StringBuilder();
41       for(int i=0; i<results.size(); i++) {
42         if(i > 0) {
43               stringBuilder.append(",");
44           }
45         stringBuilder.append("[");
46         for(int j=0; j<results.get(i).size(); j++) {
47           if(j > 0) {
48               stringBuilder.append(",");
49           }
50           stringBuilder.append(results.get(i).get(j));
51         }
52         stringBuilder.append("]");
53       }
54       
55       System.out.println(stringBuilder.toString());
56     }
57     in.close();
58   }
59 }

 

posted @ 2017-10-25 17:23  HitAnyKey  阅读(1367)  评论(0编辑  收藏  举报