全排序
1 static void AllSort(int[] arr, string rtnStr) 2 { 3 if (arr.Length == 0) 4 { 5 Console.WriteLine(rtnStr); 6 return; 7 } 8 9 int i = -1; 10 string temp = rtnStr; 11 12 while ((++i) < arr.Length) 13 { 14 rtnStr = rtnStr + arr[i] + " "; 15 16 int[] rtnArray = GetNextArray(arr, i); 17 AllSort(rtnArray, rtnStr); 18 19 rtnStr = temp; 20 } 21 } 22 23 static int[] GetNextArray(int[] arr, int index) 24 { 25 int[] rtnArray = arr.Where(p => p != arr[index]).ToArray(); 26 27 return rtnArray; 28 }
从M个数取N个数
1 static void FetchNumN(int[] arr, string rtnStr, int depth, int num) 2 { 3 if (depth == num) 4 { 5 Console.WriteLine(rtnStr); 6 return; 7 } 8 9 int i = -1; 10 string tempStr = rtnStr; 11 int tempDepth = depth; 12 13 while ((++i) < arr.Length) 14 { 15 rtnStr = rtnStr + arr[i] + " "; 16 depth++; 17 18 19 int[] rtnArray = GetNextFetchArray(arr, i); 20 FetchNumN(rtnArray, rtnStr, depth, num); 21 22 rtnStr = tempStr; 23 depth = tempDepth; 24 } 25 } 26 27 static int[] GetNextFetchArray(int[] arr, int index) 28 { 29 int[] rtnArray = new int[arr.Length - index - 1]; 30 int j = -1; 31 for (int i = index + 1; i < arr.Length; i++) 32 { 33 rtnArray[++j] = arr[i]; 34 } 35 36 return rtnArray; 37 }
调用方式
1 int[] array = new int[] { 1, 2, 3, 4, 5 }; 2 AllSort(array, ""); 3 FetchNumN(array, "", 0, 3);