C#深度优先做数字的全排列
生活随笔
收集整理的這篇文章主要介紹了
C#深度优先做数字的全排列
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
問題描述
輸入1~9之間的數字,就可以做這個數字以下所有數字的全排列。
算法思想
1******:
比如1-5之間數字的全排列,把1放在第一位上,然后后面的數字從小到大排列;
排列好之后開始倒序取兩個數字在末尾進行全排列;
從末尾開始取三個數字進行全排列;
從末尾開始取四個數字進行全排列;
。。。。。直到從末尾開始取到第二個數字進行全排列為止。
2*****:同1開頭的全排列步驟;
3*****:同1開頭的全排列步驟;
。
。
。
最后完成所有的全排列。
C#代碼
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;namespace 深度優先遍歷 {class Program{static int n;static int[] a = new int[10];static int[] book = new int[10];static void Main(string[] args){//深度優先做全排列Console.WriteLine("請輸入n的值(1-9):");n = Convert.ToInt32(Console.ReadLine());Console.WriteLine("對1-" + n + "之間的數字進行全排列:");Dfs(1);Console.ReadKey();}public static void Dfs(int step) //1~9數字的全排列{ if (step == n + 1){for (int i = 1; i <= n; i++){Console.Write(a[i]); }Console.WriteLine(); return;}for (int i = 1; i <= n; i++){ if (book[i] == 0) {a[step] = i;book[i] = 1;Dfs(step + 1);book[i] = 0;}}return; }} }運行結果
總結
以上是生活随笔為你收集整理的C#深度优先做数字的全排列的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C#数的全排列
- 下一篇: .NET Framework4.5下载地