Java pass by reference for Object(LeetCode 39)

本文通过LeetCode39题解析了Java中按引用传递的特点,并对比了按值传递的区别,揭示了在解决组合总和问题时如何避免因引用传递导致的错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

掉入Java 按引用传递的坑

今天在刷LeetCode的题的时候,刷到了LeetCode 39,题目描述如下:
Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

The same repeated number may be chosen from candidates unlimited number of times.

Note:

All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
Example 1:

Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
[7],
[2,2,3]
]
(以上是从LeetCode页面直接复制的)
就是在数组中选出数字组成和为target的组合,其中每个数可以重复出现。
这道题其实实现起来的思路很简单,就是用动态规划即可;
先选出一个数,candidates[i], 然后问题就变成了求target-candidates[i]的子问题。
但是在编写过程中,我一开始的代码如下:

class Solution {
    public List<List<Integer>> res = new ArrayList<>();
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        List<Integer> tmp = new ArrayList<>();
        rest(candidates,target,tmp,0);
        return res;
    }
    public void rest(int[] candidates, int target, List<Integer> mid,int index){
        if(target == 0){
            res.add(mid);//!!!!!!!!!!!!!!!!!!
            return;
        }
        if(target < candidates[0]) return;
        for(int i = index; i < candidates.length; i++){
            if(candidates[i] <= target){
                mid.add(candidates[i]);
                rest(candidates,target-candidates[i],mid,i); 
                mid.remove(mid.size()-1);
            }
            else return;
        }
    }
}

这样的结果运行:
在这里插入图片描述

我开始使用Java的时间并不是很长,觉得自己思路没有什么问题,但是,怎么就找不出bug,无奈开始看别人的代码,然后!!!!!!!!!!!
修改如下:

if(target == 0){
            res.add(new ArrayList<Integer>(mid));!!!!!!!!!
            return;
        }

之后,多方搜集资料,学习到了Java函数的传递机制;
对于Object类(e.g List)的参数在传入函数的时候,是通过引用传递的,也就是说,相当于传递了地址,相当于C++里面的指针,所以,每次在函数内对传入的地址所指内容进行修改后,退出函数后这个修改的影响会一直存在。
但是,对于int,char这些基本类型,在作为参数传递时,是按照值传递的,也就是,在函数内对其的改变,退出函数后并不会影响其本身的值。

如有不对的地方,请大家帮忙改正,谢谢

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值