简体   繁体   English

在pickTrees中返回treeHelper方法时应该传递什么作为“树”?

[英]What should be passed as "tree" when returning the treeHelper method in pickTrees?

Here is the question: you build homes out of wood and you need material from a nearby forest.问题来了:你用木头建造房屋,你需要来自附近森林的材料。 however, you want to avoid deforestation, so you decide for each tree you cut down, you'll leave its neighbors alone, giving the forest time to recover.但是,您想避免砍伐森林,因此您决定每砍伐一棵树,就不要管它的邻居,让森林有时间恢复。 however, you still need as much wood as possible, so you have to be careful about which trees you pick to cut down.但是,您仍然需要尽可能多的木材,因此您必须小心选择要砍伐的树木。 write picktrees, which takes in an array of n trees arr where arr[i] represents how much wood you can harvest by cutting down tree i.编写 picktrees,它接收 n 棵树 arr 的数组,其中 arr[i] 表示通过砍伐树 i 可以收获多少木材。 it should return the max amount of wood you can harvest while following the rule of skipping neighbors:它应该返回你可以收获的最大木材量,同时遵循跳过邻居的规则:

here is my code so far到目前为止,这是我的代码

public static int pickTrees(int[] arr) {
    return treeHelper(arr, ?);
}

public static int treeHelper(int[] arr, int tree){
    if (arr.length < tree){
        return 0;
    }
    if ((arr.length)-1 == tree){
        return 1;
    }
    int sum = arr[tree]+treeHelper(arr, tree+2);

    int otherSum = arr[tree+1]+treeHelper(arr, tree+3);

    return Math.max(sum, otherSum);

}

Tree is supposed to be the index of the array that is being "cut down" and added to the variables sum and other sum.树应该是被“削减”并添加到变量 sum 和其他 sum 的数组的索引。 Because I define it in the treeHelper method, when using it in the pickTrees method, I am unsure what should be passed as tree.因为我在 treeHelper 方法中定义它,所以在 pickTrees 方法中使用它时,我不确定应该将什么作为树传递。 When I used arr.length, I got an out of bounds error, which makes sense because the base cases will never be true/reached.当我使用 arr.length 时,我得到了一个越界错误,这是有道理的,因为基本情况永远不会是真的/达到。

Try passing Set of Integer pickedTrees as the second parameter treeHelper.尝试通过 Set of Integer PickTrees 作为第二个参数 treeHelper。

Try continuing from here, first try to understand what the treeHelper return value should mean.尝试从这里继续,首先尝试理解 treeHelper 返回值的含义。

(I'm answering with a hint and not the full solution because I think learning by doing is the best kind of learning) (我的回答是提示而不是完整的解决方案,因为我认为边做边学是最好的学习方式)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM