Leetcode 494 蛮力递归解决方案使用变量作为属性,但当我将其作为参数传递时不起作用

Leetcode 494 Brute force recursive solution works with a variable as a attribute but doesn't work when I pass it as parameter

提问人:alpha 提问时间:11/15/2021 更新时间:11/15/2021 访问量:40

问:

我在这里附上了解决方案。第一个有效,但第二个无效。唯一的变化是,我已将结果变量作为具有全局范围的属性移动到帮助程序函数中的参数。

class Solution {
    int result = 0;
    
    public int findTargetSumWays(int[] nums, int S) {
        if (nums == null || nums.length == 0) return result;
        helper(nums, S, 0, 0);
        return result;
    }
    
    public void helper(int[] nums, int target, int pos, long eval){
        if (pos == nums.length) {
            if (target == eval) result++;
            return;
        }
        helper(nums, target, pos + 1, eval + nums[pos]);
        helper(nums, target, pos + 1, eval - nums[pos]);
    }
}
class Solution {
    
    public int findTargetSumWays(int[] nums, int S) {
        int result = 0;
        if (nums == null || nums.length == 0) return result;
        helper(nums, S, 0, 0, result);
        return result;
    }
    
    public void helper(int[] nums, int target, int pos, long eval, int result){
        if (pos == nums.length) {
            if (target == eval) result++;
            return;
        }
        helper(nums, target, pos + 1, eval + nums[pos], result);
        helper(nums, target, pos + 1, eval - nums[pos], result);
    }
}
Java 递归 参数 作用域 按值传递

评论


答:

0赞 Florian S. 11/15/2021 #1

原语(如你的例子中的 int)在 Java 中按值传递。在第一个解决方案中,它是一个类属性。在第二个解决方案中,该值在 findTargetSumWays() 中声明,其值在 helper() 中修改。这无法以您实现它的方式工作

而不是:

int i=0;
modifyValue(i);

它应该是:

int i=0;
i = modifyValue(i);

评论

0赞 alpha 11/16/2021
快速跟进:这意味着属性或类字段作为参考传递,就像在第一个解决方案中一样,属性结果会更新?