题目如下:给定的任意多个整数,对该整数进行分组,每一组可以是一个或者多个整数,要求分组以后每一组的和不大于一个指定整数(例如100),但可以小于或者等于,如果一个单一整数大于这个指定的数字,则将这个整数拆分,按照尽量不小与指定数的原则进行拆分(例如是120,则拆分成100+20两个数,不能拆成60+60,如果是380,则拆分成100+100+100+80四个数),然后再进行分组。
弄了半天,没有通用的方法,头脑乱了,特来求解,最好有c#代码
弄了半天,没有通用的方法,头脑乱了,特来求解,最好有c#代码
inputIntList :传入的任意多个整数
max:指定的和,例如题目中的100
public List<int[]> GetIntGroup(List<int> inputIntList,int max)
{
.....
}
1.把大于100的数拆开
2.用List<int>或其它排下序
3.从大往小的分组:如排完序后为1,3,5,10,66,70,88,90,99,100,100
100的一组:100,100
小余100加上最小的:
99+1 一组
90+3+5 一组
88+10 一组
70 一组
66 一组家用电脑,没VS,只能给个思路
70%MAX+20%MAX,
...
...
50%MAX+40%MAX.
查看剩下的级别应该少于4个(除去100%,和90%,其他配对后,两个级别只有一个级别有剩余)
假设剩下10%,40%,60%,70%四个级别
判断级别10 + 70<90,直接加
判断级别40 + 60>90,加后拆分拆分后标志级别,重复以上计算能保证所有组在90%以上,当然最后一组除外。方法2:最满分组
将整数相加,将结果拆分,每拆分一组就是一个满组。
static void Main(string[] args)
{
List<int> list = new List<int>();
list.Add(60);
list.Add(80);
list.Add(120);
list.Add(270);
list.Add(340);
list.Add(410);
int max = 100;
foreach (int[] a in GetIntGroup(list, max))
{
foreach (int i in a)
Console.Write(i + " ");
Console.WriteLine();
}
}
public static List<int[]> GetIntGroup(List<int> inputIntList, int max)
{
List<int[]> listResult = new List<int[]>();
List<int> list = new List<int>();
foreach (int i in inputIntList)
{
if (i <= max)
list.Add(i);
else
{
int t = i;
while (t > max)
{
list.Add(max);
t -= max;
}
list.Add(t);
}
}
list.Sort();
for (int i = list.Count - 1; i >= 0; i--)
{
if (list[i] == max)
listResult.Add(new int[] { list[i] });
else
{
if (list[i] != -1)
{
List<int> listTemp = new List<int>();
listTemp.Add(list[i]);
int t = max - list[i];
for (int j = i - 1; j >= 0; j--)
{
if (list[j] != -1)
{
if (list[j] > t)
continue;
else if (list[j] == t)
{
listTemp.Add(list[j]);
list[j] = -1;
break;
}
else
{
listTemp.Add(list[j]);
t -= list[j];
list[j] = -1;
}
}
}
listResult.Add(listTemp.ToArray());
}
}
}
return listResult;
}/*
输出:
100
100
100
100
100
100
100
100
100
100
80 20
70 10
60 40
*/