欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

[leetcode]Pascal#39;s Triangle II

发布时间:2023/12/9 编程问答 50 豆豆
生活随笔 收集整理的这篇文章主要介绍了 [leetcode]Pascal#39;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?


思路:

the mth element of the nth row of the Pascal's triangle is C(n, m) = n!/(m! * (n-m)!)

C(n, m-1) = n!/((m-1)! * (n-m+1)!)

so C(n, m) = C(n, m-1) * (n-m+1) / m

In additional, C(n, m) == C(n, n-m)

代码:

public List<Integer> getRow(int rowIndex) {if(rowIndex < 0)return new ArrayList<Integer>();int num = rowIndex+1;List<Integer> list = new ArrayList<Integer>(num);double [] factor = new double[num];double result = 1;factor[0] = 1;list.add(1);for(int i=1; i<num ; i++){result = result*(num-i)/i;factor[i] = result;list.add((int)factor[i]);}return list;}

版权声明:本文博主原创文章,博客,未经同意不得转载。

总结

以上是生活随笔为你收集整理的[leetcode]Pascal#39;s Triangle II的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。