问题:给出一个数字' a'和数字' b'。找到尺寸为' a'的所有组合。并且组合中的数字之和应该等于' b'。
示例:a = 3,b = 5.为简单起见,仅考虑整数。 组合 - {(0,0,5},(1,1,3),(1,2,2),(0,1,4),(0,2,3)}。 {1,3,1}不是有效组合,因为(1,1,3)已经在解决方案中。
这是我的解决方案。
public void CombinationsMain()
{
Console.Write("Enter the target sum: ");
string tsum = Console.ReadLine();
Console.Write("Enter the number of combinations: ");
string combination = Console.ReadLine();
int targetsum;
Int32.TryParse(tsum, out targetsum);
int m;
Int32.TryParse(combination, out m);
int[] arr = new int[m];
CombinationsUtil(targetsum, 0, arr);
Console.ReadLine();
}
public void CombinationsUtil(int targetsum, int index, int[] arr)
{
//check if the length of the current index is same as arr length and sum
//before printing the combination
//SumofArrayElements ignores the combination like {0 0 5 0} { 0 5 0 0} and will print only { 0 0 0 5}
if (index == arr.Length && SumOfArrayElements(arr, targetsum))
{
for (int i = 0; i < arr.Length; i++)
Console.Write(arr[i]);
Console.WriteLine();
}
for (int i = 0; i <= targetsum && index < arr.Length; i++)
{
arr[index] = i;
CombinationsUtil(targetsum, index + 1, arr);
}
}
//returns true or false comparing sum of elements of array and given target sum
public bool SumOfArrayElements(int[] arr, int targetsum)
{
int sum = 0;
for (int i = 0; i < arr.Length; i++)
{
if (i < arr.Length-1 && arr[i] > arr[i + 1])
return false;
sum += arr[i];
}
return sum == targetsum;
}
时间复杂度为O(n ^ m)(此处为n为targetsum)。可以进一步优化还是这是我能做的最好的?感谢您的投入。