搜狗面试题:从N个正实数中选若干个数之和最接近M的递归实现

//搜狗:有N个正实数(注意是实数,大小升序排列) x1 , x2 ... xN,另有一个实数M。
//需要选出若干个x,使这几个x的和与 M 最接近。 请描述实现算法,并指出算法复杂度。
public void FindDouble(double[] A,bool[] Exsits, int N,double M,int i,double PreCurrSum,bool Exists)
{
double theCurrSum = PreCurrSum + (Exists ? A[i - 1] : 0);
Exsits[i - 1] = Exists;
double theNewDelta = Math.Abs(theCurrSum - M);
if (theNewDelta < MinDelta)
{
MinDelta = theNewDelta;
for (int j = i + 1; j <= N; j++)
{
Exsits[j - 1] = false;
}
CopyResult(Exsits, N);
}
if (i < N)
{
FindDouble(A, Exsits, N, M, i + 1, theCurrSum,false);
FindDouble(A, Exsits, N, M, i + 1, theCurrSum,true);
}
}
private void CopyResult(bool[] Exsits, int N)
{
for (int i = 0; i < N; i++)
{
Exist[i] = Exsits[i];
}
}
private void button3_Click(object sender, EventArgs e)
{
double[] A = new double[] {1.5,2.5,3.0,5.0,8.0,9.0};
bool[] E = new bool[] { false, false, false, false, false, false };
Exist = new bool[6];
MinDelta = double.MaxValue;
FindDouble(A, E, 6, 12, 1, 0.0, false);
FindDouble(A, E, 6, 12, 1,0.0, true);
}

PS:原来这种递归处理是典型的背包问题,长见识了。

你可能感兴趣的:(面试题)