搜狗:有N个正实数(注意是实数,大小升序排列) x1 , x2 ... xN,另有一个实数M。 需要选出若干个x,使这几个x的和与 M 最接近。 请描述实现算法,并指出算法复杂度。
public class SearchN
{private boolean dataflag[];
private double data[];
private double min;
private double m;
public void setDataflag(boolean[] dataflag) {
this.dataflag = dataflag;
}
public void setData(double[] data) {
this.data = data;
}
public void setM(double m) {
this.m = m;
this.min=m;
}
public void search(int i,double result,boolean falgtemp[],boolean flag)
{
if(flag)result+=data[i];
falgtemp[i]=flag;
if(Math.abs(m-result)<min)
{
min=m-result;
System.arraycopy(falgtemp, 0, dataflag, 0, data.length);
}
if(i<data.length-1)
{
search(i+1,result,falgtemp,true);
search(i+1,result,falgtemp,false);
}
}
public void doWork()
{
search(0,0,new boolean[data.length],true);
search(0,0,new boolean[data.length],false);
}
public void displayHeap()
{
for(int i=0;i<data.length;i++)
if(dataflag[i])System.out.print(data[i]+" ");
}
public static void main(String[] args)
{
double[] A = new double[] {1.5,2.5,3.0};
boolean[] E = new boolean[A.length];
SearchN n=new SearchN();
n.setData(A);n.setDataflag(E);n.setM(5.5);
n.doWork();
n.displayHeap();
}
}