static int n; static void Main(string[] args) { Console.WriteLine("输入1-9的数字"); n = Convert.ToInt32( Console.ReadLine()); dfs(); Console.ReadKey(); } static int[] book = new int[10];//用来标志数有没被用 static int[] result = new int[10];//记录结果 static void dfs(int step = 1) { if (step > n) { foreach (var val in result) { if (val != 0) { Console.Write(val + " "); } } Console.WriteLine(); return;//退出口 } for (int i = 1; i <= n; i++) { if (book[i] == 0) {//这个数字没被用,则用它 result[step] = i; book[i] = 1; dfs(step+1); //从上一步回来了,取回这个数才能尝试下一个数 book[i] = 0; } } }
深度优先搜索的思想,先遍历到最尾处出现一种情况了再返回
递归的方式实现,其实就是栈的方式,涉及深度优先搜索的采用栈来解决
这种计算遍历了所有情况