要求组合形式之和不能大于该值 假如有6个数据:1、2、3、4、5、6
给定值为10,最优的组合为4和6
给定值为5,最优的组合为5假如有6个数据:8.1、1.3、1.5、7.0、0.3、6.6
给定值为10,最优的组合为8.1、1.5和0.3
给定值为7,最优的组合为7
给定值为10,最优的组合为4和6
给定值为5,最优的组合为5假如有6个数据:8.1、1.3、1.5、7.0、0.3、6.6
给定值为10,最优的组合为8.1、1.5和0.3
给定值为7,最优的组合为7
static void Main(string[] args)
{
List<double> list = Find(new double[] { 8.1, 1.3, 1.5, 7.0, 0.3, 6.6 }, 10);
foreach (double d in list)
Console.WriteLine(d);
} static List<double> Find(double[] dArray, double d)
{
if (dArray.Length < 1)
return null;
List<double> list = new List<double>();
int index = Array.IndexOf(dArray, d);
if (index > -1)
{
list.Add(dArray[index]);
return list;
}
double temp = d;
Array.Sort(dArray);
for (int i = dArray.Length - 1; i > -1; i--)
{
if (dArray[i] <= temp)
{
list.Add(dArray[i]);
temp -= dArray[i];
}
}
return list;
}
List<double> list = Find(new double[] { 8.1, 1.3, 1.58, 7.0, 0.3, 6.6 }, 8.2);
算出的结果是8.1,
而事实上,我要的结果是1.58和6.6。1.58+6.6=8.18,最接近8.2
static void Main(string[] args)
{
Find(new double[] { 8.1, 1.3, 1.58, 7.0, 0.3, 6.6 }, 8.2);
} static void Find(double[] dArray, double d)
{
if (dArray.Length < 1)
{
Console.WriteLine("数组无效");
return;
}
int index = Array.IndexOf(dArray, d);
if (index > -1)
{
Console.WriteLine(dArray[index]);
return;
}
Array.Sort(dArray);
List<double> listMinus = new List<double>();
List<List<double>> listCom = new List<List<double>>();
double minus = dArray[dArray.Length - 1];
for (int i = dArray.Length - 1; i > -1; i--)
{
double temp = d;
if (dArray[i] <= temp)
{
List<double> list = new List<double>();
list.Add(dArray[i]);
temp -= dArray[i];
for (int j = i - 1; j > -1; j--)
{
if (dArray[j] <= temp)
{
list.Add(dArray[j]);
temp -= dArray[j];
}
}
listCom.Add(list);
listMinus.Add(temp);
if (temp < minus)
minus = temp;
}
}
for (int i = 0; i < listMinus.Count; i++)
{
if (listMinus[i] == minus)
{
Console.Write("可能的组合有:");
foreach (double d1 in listCom[i])
Console.Write("{0} ", d1);
Console.WriteLine();
}
}
}