我試圖從一個代表數字的int陣列中生成所有可能的數字。
對于一個例子 arr= new int[]{1,2} 我得到了以下結果。
1
2
11
21 21
12 12
22
count =6.
對于一個例子arr= new int[]{1,2,3},我得到以下結果。
1 2 3 11 21 31 12 22 32 13 23 33 111 211 311 121 221 321 131 231 331 112 212 312 122 222 322 132 232 332 113 213 313 123 223 323 133 233 333
count =39.
我真的不確定這是否是我應該得到的正確的條目數,特別是對于更大尺寸的輸入陣列。
是否有任何我不知道的數學公式?我知道n!并不適用于這種情況。
下面是我寫的計算所有可能的組合的代碼
class HelloWorld {
static void Main() /span> {
var output = GenerateAllCombinations(new int[] {1, 2,3})。)
foreach(var o in output )
{
Console.WriteLine(o)。
}
Console.WriteLine(output.Count)。
}
public static HashSet<string> GenerateAllCombinations(span class="hljs-built_in">int[] nums){
//將int陣列轉換為字串陣列。
var strNums=nums.Select(x =>x.ToString()).ToArray()。
var cach = new HashSet<string>(strNums)。
var output = new HashSet<string>(strNums)。
for(int u=1; u< strNums.Length;u )
{
var temp = new HashSet<string>()。
for(int i=0; i<strNums.Length;i )
{
foreach(var h in cach )
{
temp.Add(h strNums[i])。
}
}
cach=new HashSet<string>(temp)。
output.UnionWith(temp)。
}
return output;
}
}
uj5u.com熱心網友回復:
對于n不同的數字,
- 個位數的數量=
n - 2位數的數量=
n^2 - 3位數的計數=
n^3 n位數的計數=n^n。
獨立數字總數=n n^2 n^3... n^n=n * ((n^n) - 1) / (n-1)(使用簡單幾何級數求和法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/321126.html
標籤:
上一篇:如何將重復的列轉為行Pandas
