119. Pascal's Triangle II

网友投稿 587 2022-11-11

119. Pascal's Triangle II

119. Pascal's Triangle II

Given an index k, return the kth row of the Pascal’s triangle.

For example, given k = 3, Return [1,3,3,1].

Note: Could you optimize your algorithm to use only O(k) extra space?

class Solution { public List getRow(int rowIndex) { List list = new ArrayList (rowIndex + 1); list.add(1); if (rowIndex == 0) { return list; } list.add(1); if (rowIndex == 1) { return list; } for (int i = 2; i <= rowIndex; ++i) { list.add(1); for (int j = i - 1; j > 0; --j) { list.set(j, list.get(j) + list.get(j - 1)); } } return list; }}

class Solution { public List getRow(int rowIndex) { List row = new ArrayList<>(); for(int i=0;i<=rowIndex;++i) row.add(findnCr(rowIndex,i)); return row; } public int findnCr(int n, int r){ r = Math.min(r,n-r); double ans=1; for (int i = 0; i < r; ++i){ ans *= (n - i); ans /= (i + 1); } return (int)ans; }}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:117. Populating Next Right Pointers in Each Node II
下一篇:springboot创建线程池的两种方式小结
相关文章

 发表评论

暂时没有评论,来抢沙发吧~