目前我有一个包含13个值的数组,我希望找到它的所有排列,并排除那些超出给定阈值的求和值。问题是它有很多价值,它永远不会完成。有没有办法优化我的东西?
public class formPermut
{
public void swapTwoNumber(ref int a, ref int b)
{
int temp = a;
a = b;
b = temp;
}
public void prnPermut(int[] list, int k, int m)
{
int i;
if (k == m)
{
for (i = 0; i <= m; i++)
Console.Write("{0}", list[i]);
Console.Write(" ");
}
else
for (i = k; i <= m; i++)
{
swapTwoNumber(ref list[k], ref list[i]);
prnPermut(list, k + 1, m);
swapTwoNumber(ref list[k], ref list[i]);
}
}
}
public static void RecExercise11()
{
int n, i;
formPermut test = new formPermut();
int[] arr1 = new int[13];
Console.WriteLine("\n\n Recursion : Generate all possible permutations of an array :");
Console.WriteLine("------------------------------------------------------------------");
Console.Write(" Input the number of elements to store in the array [maximum 13 digits ] :");
n = Convert.ToInt32(Console.ReadLine());
Console.Write(" Input {0} number of elements in the array :\n", n);
for (i = 0; i < n; i++)
{
Console.Write(" element - {0} : ", i);
arr1[i] = Convert.ToInt32(Console.ReadLine());
}
Console.Write("\n The Permutations with a combination of {0} digits are : \n", n);
test.prnPermut(arr1, 0, n - 1);
Console.Write("\n\n");
}
}
}
答案 0 :(得分:0)
所以问题是你需要排除总和大于阈值的排列是回溯的完美候选者(不要搜索这个词),想想加速这个的方法(有n!排列)所以它不会在一段时间内完成)。
想象一下,这就像一棵树,树叶是排列本身并回答:
答案 1 :(得分:0)
我建议你看看从这里使用Permutation库
https://www.codeproject.com/Articles/26050/Permutations-Combinations-and-Variations-using-C-G
然后在此基础上编写过滤。