Java pass by reference for Object(LeetCode 39)

掉入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这些基本类型,在作为参数传递时,是按照值传递的,也就是,在函数内对其的改变,退出函数后并不会影响其本身的值。

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

猜你喜欢

转载自blog.csdn.net/BALAHuN/article/details/89064868