1. 程式人生 > >在0~N個數字中,取指定個數的不重復數字,要求這些數字的和為指定值,求所有結果

在0~N個數字中,取指定個數的不重復數字,要求這些數字的和為指定值,求所有結果

readline tco write span count string rgs logs index

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 
  6 namespace ConsoleApp1 {
  7     class Program {
  8         static void Main(string[] args) {
  9 
 10             // 防止出現隨機值無法組合
 11             while (ResDic.Count == 0) {
 12 
 13
Con = 10; 14 // 初始化數組長度 15 int Len = 30; 16 Arr = new int[Len]; 17 Temp = new int[Con]; 18 19 // 最小的數 20 int Min = (Con - 1) * Con / 2; 21 // 最大的數 22 int
Max = (Len - Con + 1 + Len) * Con / 2; 23 // 獲取範圍內的一個隨機數 24 Random random = new Random(); 25 Sum = random.Next(Min, Max + 1); 26 27 // 28 GetConNum(0, 0); 29 } 30 31 Console.WriteLine(Sum);
32 Console.WriteLine(ResDic.Count); 33 34 //for (int i = 0; i < ResDic.Count; i++) { 35 // Console.WriteLine(ResDic[i]); 36 //} 37 38 Console.ReadLine(); 39 } 40 41 /// <summary> 42 /// 用於存儲所有結果 43 /// </summary> 44 private static Dictionary<int, string> ResDic = new Dictionary<int, string>(); 45 /// <summary> 46 /// 用於取值 47 /// </summary> 48 private static int[] Arr; 49 /// <summary> 50 /// 用於存值 51 /// </summary> 52 private static int[] Temp; 53 /// <summary> 54 /// 要取的數字個數 55 /// </summary> 56 private static int Con; 57 /// <summary> 58 /// 總和 59 /// </summary> 60 private static int Sum; 61 62 /// <summary> 63 /// 在Arr中取Con個不重復的數字 64 /// </summary> 65 /// <param name="index"></param> 66 /// <param name="init"></param> 67 private static void GetConNum(int index, int init) { 68 69 if (index >= Con) { 70 // 計算這些數字的和 71 int Tsum = 0; 72 for (int i = 0; i < Temp.Length; i++) 73 Tsum += Temp[i]; 74 75 // 若和與Sum相同,全排列存入所有排列可能 76 if (Tsum == Sum) 77 ListArray(0); 78 79 return; 80 } 81 82 for (int i = init; i < Arr.Length; i++) { 83 Temp[index] = i; 84 GetConNum(index + 1, i + 1); 85 } 86 } 87 88 /// <summary> 89 /// 對數組Temp進行全排列 90 /// </summary> 91 /// <param name="index"></param> 92 private static void ListArray(int index) { 93 // 一次排列結束後 94 if (index >= Temp.Length) { 95 // 取出當前的排列結果,拼成字符串 96 string str = ""; 97 for (int i = 0; i < Temp.Length; i++) { 98 str += Temp[i]; 99 if (i < Temp.Length - 1) 100 str += ","; 101 } 102 // 將結果存入字典 103 ResDic.Add(ResDic.Count, str); 104 return; 105 } 106 107 int t = Temp[index]; 108 109 // 交換位置 110 for (int i = index; i < Temp.Length; i++) { 111 Temp[index] = Temp[i]; 112 Temp[i] = t; 113 ListArray(index + 1); 114 115             // 還原 116 Temp[i] = Temp[index]; 117 Temp[index] = t; 118 119 } 120 } 121 } 122 }

在0~N個數字中,取指定個數的不重復數字,要求這些數字的和為指定值,求所有結果