Algorithm-Arrays-6 Kth pascal triangle
来源:互联网 发布:美食纪录片 知乎 编辑:程序博客网 时间:2024/06/02 05:54
1. 题目: Kth Row of Pascal’s Triangle
此处有关于该问题的类似解法。
Given an index k, return the kth row of the Pascal’s triangle.
Pascal’s triangle : To generate A[C] in row R, sum up A’[C] and A’[C-1] from previous row R - 1.
Example:
Input : k = 3
Return : [1,3,3,1]
NOTE : k is 0 based. k = 0, corresponds to the row [1].
Note:Could you optimize your algorithm to use only O(k) extra space?输入为第k行,输出改行的元素值(k是从0开始的下标)。
2. 解题思路
1). 法1
public List<Integer> getRow(int rowIndex) { ArrayList<Integer> result = new ArrayList<>(); if (rowIndex < 0) return result; result.add(1); for (int i = 1; i <= rowIndex; i++) { // 当前循环的result可由上一层循环的result得到 for (int j = result.size() - 2; j >= 0; j--) { result.set(j + 1, result.get(j + 1) + result.get(j)); } result.add(1); } return result; }
2). 法2
/* * C(line, i) = line! / ( (line-i)! * i! ) C(line, i-1) = line! / ( (line - * i + 1)! * (i-1)! ) We can derive following expression from above two * expressions. C(line, i) = C(line, i-1) * (line - i + 1) / i * * So C(line, i) can be calculated from C(line, i-1) in O(1) time */ public ArrayList<Integer> getRow1(int A) { ArrayList<Integer> list = new ArrayList<Integer>(A + 1); int line = A + 1; int C = 1; // used to represent C(line, i) for (int i = 1; i <= line; i++) { list.add(C); // The first value in a line is always 1 C = C * (line - i) / i; } return list; }
阅读全文
0 0
- Algorithm-Arrays-6 Kth pascal triangle
- Arrays-----118. Pascal's Triangle
- Pascal Triangle
- Pascal Triangle
- 【Leetcode】Pascal's Triangle (Pascal)
- Pascal's Triangle、Pascal's Triangle II
- Pascal's Triangle , Pascal's Triangle II
- Pascal's Triangle Pascal's Triangle||
- Pascal's Triangle & Pascal's Triangle II
- Pascal's Triangle && Pascal's Triangle II
- Give an O(log m + log n) algorithm to find the kth element in two sorted arrays
- LeetCode Pascal's Triangle
- [Leetcode] Pascal's Triangle
- LeetCode: Pascal's Triangle
- Pascal's Triangle
- Pascal's Triangle II
- [LeetCode] Pascal's Triangle
- 【leetcode】Pascal's Triangle
- makefile
- 现在Java程序员面试有多偏,一份面试题让你跪倒在面试官面前
- 性能与优化命令
- 网络管理
- FAT32文件系统之结构初探(一)
- Algorithm-Arrays-6 Kth pascal triangle
- Surrounded Regions问题及解法
- POSIX多线程程序设计学习篇之三(条件变量)
- ZOJ 3194 Coverage【贪心】
- Unity3D shader(12)——Fragment Shader(模型颜色变化)
- A. Arya and Bran
- 百度之星初赛(A) 1 数学 5 模拟 6 判连通(BFS)
- GNU计划的了解
- 《算法导论》第五章-第1节_练习(参考答案)