您的位置:首页 > 新闻 > 会展 > java-杨辉三角

java-杨辉三角

2025/6/4 16:13:22 来源:https://blog.csdn.net/t1750982356/article/details/140876004  浏览:    关键词:java-杨辉三角

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

示例 1:

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

示例 2:

输入: numRows = 1
输出: [[1]]

思路:用动态规划

class Solution {public List<List<Integer>> generate(int numRows) {List<List<Integer>> res=new ArrayList<>();for(int i=0;i<numRows;i++){List<Integer> ans=new ArrayList<>();for(int j=0;j<=i;j++){if(j==0||j==i){ans.add(1);}else{ans.add(res.get(i-1).get(j-1)+res.get(i-1).get(j));}}res.add(ans);}return res;}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com