Leetcode刷题———————杨辉三角(递归公式的实现、List的按地址传值)

16 篇文章 0 订阅
本文通过解决LeetCode的杨辉三角问题,探讨了递归公式的实现,并重点分析了Java中List按地址传值导致的问题及其解决方案,最终通过深拷贝确保了正确输出。
摘要由CSDN通过智能技术生成

刷Leetcode的递归题目,题目为:

给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。

 

在杨辉三角中,每个数是它左上方和右上方的数的和。

示例:

输入: 5
输出:
[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

 

本题的解题关键要推出递归实现的公式,在此地不再赘述。具体可参考以下链接:

杨辉三角的递归关系的详细推倒过程 点击这里

按照以上步骤,成功实现,不过输出的结果却不正确,实现代码为:

// "static void main" must be defined in a public class.
public class Main {
    public static void main(String[] args) {
        System.out.println("Hello World!");
        List<List<Integer>> list =new ArrayList<>();
        List<Integer> l=new ArrayList<>();
        for(int i=1;i<=5;i++){
            l.clear();
            for(int j=1;j<=i;j++){
                l.add(helper(i,j));               
            }
            list.add(l);
        }
        System.out.println(list);    

    }
    
    private static int helper( int i,int j){
        int x=0;
        if( j==1 || i==j){
            return 1;
        }
        
        
        return helper(i-1,j-1)+helper(i-1,j);
    }
    
    
}

输出的结果为:

[[1, 4, 6, 4, 1], 
[1, 4, 6, 4, 1],
 [1, 4, 6, 4, 1],
 [1, 4, 6, 4, 1],
 [1, 4, 6, 4, 1]]

经过一番排查与测试,得出当 文中列表变量 l 的值改变时,已经被赋值的list变量对应的值也会进行变化,因此得出结论:List的值在此刻是通过地址传值的,

经过一番查找,找到解决方法为:

List copy = List.copyOf(list);

The only conditions are that the given Collection mustn’t be null, and it mustn’t contain any null elements.

将代码中对应复制代码进行修改:

list.add(List.copyOf(l));

成功输出正确结果

 

参考链接:

https://www.baeldung.com/java-copy-list-to-another

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值