Sevendays

不积跬步,无以至千里;不积小流,无以成江海。

导航

一道不怎么容易的算法题解决办法

Posted on 2010-03-18 22:46  Sevendays  阅读(2847)  评论(14编辑  收藏  举报

 

题目: 输入一个整数N,程序输出数字1,2,3…N的全部排列。例如,如果N=3,那么数字1,2,3的全部排列如下:

1 2 3
1 3 2
2 1 3
2 3 1
3 1 2

3 2 1

 

 

这道算法题,当我看到时说实在的优有点懵,感觉不是那么难,但是又无从下手。昨天晚上忽然心血来潮写了下。

思路:分析题目,可以将整数N转换成一个有N个结点的,然后从第一个结点开始,一个一个加入需要生成的序列中,例如,首先添加1,生成的路径只有一种,然后将2添加进来,这样对已有的路径中添加2,在1的前面都可以添加,这样就生成了两种路径了,此次类推。。。

 

                                                                                                       已有的 路径

添加1开始:                                                                                             1

添加2(这时有两个位置可以插入2)                                          2,1                                  1,2

添加3(这时每个已有路径里可以插入3的位置有三个位置) 3,2,1   2,3,1     2,1,3         3,1,2    1,3,2   1,2,3

…………                                                                              …………                               …………

以下是源码:

 

代码
1 public class Seven
2 {
3 private StringBuilder pathInfoStr = new StringBuilder();
4
5 private int cnt = 0;//记录路径的个数
6  
7 public int Cnt
8 {
9 get { return cnt; }
10 set { cnt = value; }
11 }
12 /// <summary>
13 /// 输入N的值
14 /// </summary>
15   public int N { get; set; }
16
17
18 int idnALL = 0;
19 t;> List<List<int>> allPathInfo = new List<List<int>>();
20
21 /// <summary>
22 /// 生成各种路径
23 /// </summary>
24   private void Create()
25 {
26 int i = 1;
27 while (i <= N)
28 {
29 if (allPathInfo.Count == 0)
30 {
31 List<int> tt = new List<int>();
32 tt.Add(i);
33 allPathInfo.Add(tt);
34 }
35 else
36 {
37 idnALL = allPathInfo.Count;
38 for (int j = 0; j < idnALL; j++)
39 {
40 List<int> path = allPathInfo[j];
41 int idx = 0;
42 while (idx < path.Count)
43 {
44 List<int> newPath = path.GetRange(0, path.Count);
45 newPath.Insert(idx, i);
46 allPathInfo.Add(newPath);
47 idx++;
48 }
49 path.Insert(idx, i);
50 }
51 }
52 i++;
53 }
54 }
55 /// <summary>
56 /// 将完整路径信息转换成字符串输出
57 /// </summary>
58   private void showPathString()
59 {
60 foreach (List<int> tempList in allPathInfo)
61 {
62 foreach (int v in tempList)
63 {
64 pathInfoStr.Append(v.ToString());
65 pathInfoStr.Append(" ");
66 }
67 pathInfoStr.Append("\n<br/>");
68 cnt++;
69 }
70 }
71
72 /// <summary>
73 /// 生成路径并转换成字符串输出
74 /// </summary>
75 /// <returns></returns>
76   public string getResult()
77 {
78 Create();
79 showPathString();
80 return pathInfoStr.ToString();
81 }
82 }