背包问题递归java

时间:2022-02-11 04:34:11
 public boolean PackageProblem(int[] arr,int start,int targetLeft,int target)
{
if(arr.length==0)
{
System.out.println("no Answer");
return false;
}
if(start==arr.length)
{
int[] tempArr=new int[arr.length-1];
System.arraycopy(arr, 1, tempArr, 0, arr.length-1); return PackageProblem(tempArr, 0, target, target);
}
else if(arr[start]>targetLeft)
{
return PackageProblem(arr, start+1, targetLeft, target);
}
else if(arr[start]==targetLeft)
{
System.out.println("yes has answer");
return true;
}
else{
return PackageProblem(arr, start+1, targetLeft-arr[start], target);
} }

int[] arr={11,10,8,7,5,3};
int target=21;

但是这个数组要是从大到小排好的?

int[] arr={11,8,7,5,3,10};就不行