Java 找出一个集合中有多少子集具有目标和
给定一个Java 找出一个集合中有多少子集具有目标和,java,Java,给定一个ints数组和一个目标值,找出数组中有多少子集添加到目标值 当我运行它的时候,我总是得到一些古怪的数字…有什么问题吗 public int findGoal(int[] anArray,int index, int current, int goal, String result){ //Base case: At the end of the array if (anArray.length <= index || current>goal) {
int
s数组和一个目标值,找出数组中有多少子集添加到目标值
当我运行它的时候,我总是得到一些古怪的数字…有什么问题吗
public int findGoal(int[] anArray,int index, int current, int goal, String result){
//Base case: At the end of the array
if (anArray.length <= index || current>goal) {
return count;
}
//Recursive case: If not at end iterate
for (int i = index; i < anArray.length; i++) {
if (current + anArray[i] == goal) {
count++;
} else if (current + anArray[i] < goal) {
count = findGoal(anArray, i + 1, current + anArray[i], goal, result + " " + anArray[i]);
}
}
return count;
}
public int findGoal(int[]数组,int索引,int当前,int目标,字符串结果){
//基本情况:在数组的末尾
if(anArray.length目标){
返回计数;
}
//递归案例:如果不是在末尾迭代
对于(inti=index;i
您应该演示如何调用此函数。我正在使用另一个类来调用该方法,该类使用一个扫描器来请求数组中的数字和目标值。如果您得到的是令人生厌的数字,则可能是出了问题。混合使用迭代和递归通常意味着您没有充分考虑某些问题。你有没有试过打印出你选择的值,这样你就可以看到你是否真的在检查每个子集,并且只检查一次?@user3144709我的意思是,给我们一个传递给这个函数的参数示例,似乎对索引
或当前
或目标
使用不正确的值会产生错误的答案。