将一个n元素的数组平均分为m分,是每组和相等,求最大m

来源:互联网 发布:网络推广的综合方案 编辑:程序博客网 时间:2024/03/28 21:52

网上流行的一道题目,题目如下。最终利用穷取法来递归解决的。

一个整数数组,长度为n,将其分为份,使各份的和相等,求的最大值
比如{32436} 可以分成{32436} m=1;
{3,6}{2,4,3} m=2
{3,3}{2,4}{6} m=3 所以的最大值为3

using System;using System.Collections.Generic;using System.IO;namespace ConsoleApp{    class RunClass    {        public static void Main()        {            int[] arr = new int[] { 3, 5, 2, 4, 1, 6, 3 };            int sum = 0;            foreach (int t in arr)  sum += t;            for (int m = arr.Length; m > 0; m--)            {                int[] aux = new int[arr.Length];//to instore the groupId of each value of arr                if (sum % m != 0)                    continue;                bool success = BruteTest(arr, m, aux, sum/m,sum / m, 1);                if (success)//print the result                {                    Console.WriteLine("m = {0}", m);                    foreach (int value in arr)                        Console.Write(" " + value);                    Console.WriteLine();                    foreach (int groupId in aux)                        Console.Write(" " + groupId);                    Console.WriteLine();                }            }        }        private static bool BruteTest(int[] arr, int m, int[] aux,int groupSum ,int goal, int groupId)        {            if (goal < 0)                return false;            if (goal == 0)            {                groupId++;                goal = groupSum;                if (groupId == m + 1)                     return true;            }            for (int i = 0; i < arr.Length; i++)            {                if (aux[i] != 0)                    continue;                aux[i] = groupId;                if (BruteTest(arr, m, aux,groupSum, goal - arr[i], groupId) == true)                    return true;                aux[i] = 0;            }            return false;        }    }}