您的位置:首页 > 其它

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

2010-03-18 22:46 351 查看
题目: 输入一个整数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

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

以下是源码:

代码

public class Seven
{
private StringBuilder pathInfoStr = new StringBuilder();

private int cnt = 0;//记录路径的个数

public int Cnt
{
get { return cnt; }
set { cnt = value; }
}
/// <summary>
/// 输入N的值
/// </summary>
public int N { get; set; }

int idnALL = 0;
t;>        List<List<int>> allPathInfo = new List<List<int>>();

/// <summary>
/// 生成各种路径
/// </summary>
private void Create()
{
int i = 1;
while (i <= N)
{
if (allPathInfo.Count == 0)
{
List<int> tt = new List<int>();
tt.Add(i);
allPathInfo.Add(tt);
}
else
{
idnALL = allPathInfo.Count;
for (int j = 0; j < idnALL; j++)
{
List<int> path = allPathInfo[j];
int idx = 0;
while (idx < path.Count)
{
List<int> newPath = path.GetRange(0, path.Count);
newPath.Insert(idx, i);
allPathInfo.Add(newPath);
idx++;
}
path.Insert(idx, i);
}
}
i++;
}
}
/// <summary>
/// 将完整路径信息转换成字符串输出
/// </summary>
private void showPathString()
{
foreach (List<int> tempList in allPathInfo)
{
foreach (int v in tempList)
{
pathInfoStr.Append(v.ToString());
pathInfoStr.Append("  ");
}
pathInfoStr.Append("\n<br/>");
cnt++;
}
}

/// <summary>
/// 生成路径并转换成字符串输出
/// </summary>
/// <returns></returns>
public string getResult()
{
Create();
showPathString();
return pathInfoStr.ToString();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐