刷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