一道不怎么容易的算法题解决办法
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
………… ………… …………
以下是源码:
代码
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(); } }
相关文章推荐
- Mac运行速度变慢怎么办?Mac运行速度慢解决办法
- [原创] Keil uVision5 下载程序 add flash programming algorithm选项缺少需要的算法解决办法
- 【rzxt】高手分享:死机了怎么办?路由器死机解决办法
- 【更新声卡驱动后还是没声音怎么办】_病毒导致电脑没声音的解决办法
- 电脑没有声音怎么办?电脑没声音的解决办法
- win2003文件夹没有共享选项的解决办法---win2003容易出现这种情况
- 在MyEclipse中怎么建立包中有包的解决办法
- win10手机预览版10080开始屏幕不见了怎么办?黑屏的解决办法
- 编译安装php容易出现的问题以及解决办法
- Win8.1系统无法调节屏幕亮度怎么办 Win8.1不能调节亮度的解决办法图解
- Win 2003 安装 IIS SNMP 无法复制 .vbs .dll 等文件 怎么办 解决办法
- 小算法,关于阶乘数字过大溢出的解决办法
- 利用java类的思想和并查集的方法解决同一道算法题
- iPhone白苹果怎么办?白苹果各种解决办法方法
- 程序员容易发福的原因及解决办法
- 意志消沉,记忆力减退,注意力不集中, 理解力下降,失眠,多梦,头昏,心悸等该怎么办?是否有解决的办法
- office怎么也卸载不干净,解决办法
- Win8.1声音小怎么办 Win8.1系统中声音忽大忽小问题的解决办法介绍
- 怎么解决yum安装的时候rpm包没有办法下载的问题
- 我是怎么使用最短路径算法解决动态联动问题的