2.一个整数数组,长度为n,将其分为m份,使各份的和相等,求m的最大值
比如{3,2,4,3,6} 可以分成{3,2,4,3,6} m=1;
{3,6}{2,4,3} m=2
{3,3}{2,4}{6} m=3 所以m的最大值为3
C# codes as below:
using System;
using System.Collections.Generic;
namespace ConsoleApp
{
class RunClass
{
static void Main()
{
int[] array = { 3, 2, 4, 3, 6 };
int max = new RunClass().MaxPartsNumber(array);
Console.WriteLine(max);
Console.ReadLine();
}
public int MaxPartsNumber(int[] array)
{
List<int> list = new List<int>();
list.AddRange(array);
int sum = 0;
foreach (int i in array)
{
sum += i;
}
for (int i = array.Length; i >0; i--)
{
if (sum % i == 0)
{
if (IfExist(list, sum / i, sum / i))
{
return i;
}
}
}
return 1;
}
private bool IfExist(List<int> rootList, int number, int orginalNumber)
{
if (rootList.Count == 0 && number==orginalNumber)
{
return true;
}
bool ifExist = false;
for (int i=0; i<rootList.Count;i++)
{
List<int> childList = new List<int>();
for (int j = 0; j < rootList.Count; j++)
{
if (j != i)
{
childList.Add(rootList[j]);
}
}
if (rootList[i] == number)
{
ifExist = ifExist || IfExist(childList, orginalNumber, orginalNumber);
}
else if (rootList[i] < number)
{
ifExist = ifExist || IfExist(childList, number - rootList[i], orginalNumber);
}
}
return ifExist;
}
}
}