LeetCode-118. Pascal's Triangle,119. Pascal's Triangle II
来源:互联网 发布:c语言算法比较好的书 编辑:程序博客网 时间:2024/06/01 23:13
118
Problem:
Given numRows, generate the first numRows of Pascal’s triangle.For example, given numRows = 5,Return
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
Analysis:
把握住原则:每一层的第i个位置,等于上一层第i-1与第i个位置之和。
有的题解也用另一个列表记录上一层的列表,就像一个temp。本方法没有这么做
Answer:
public class Solution { public List<List<Integer>> generate(int numRows) { List<List<Integer>> result=new LinkedList<List<Integer>>(); if(numRows==0) return result; for(int i=1;i<=numRows;i++){ List<Integer> innerlist =new LinkedList<Integer>(); innerlist.add(1); for(int j=1;j<i-1;j++){ int temp=result.get(i-2).get(j-1)+result.get(i-2).get(j); innerlist.add(temp); } if(i>1) innerlist.add(1); result.add(innerlist); } return result; }}
119
Problem:
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?
Analysis:
这个题目和上一个题目差不多,如果不考虑占用空间的话,只在上一个答案的返回改为result.get(rowIndex)即可,
Answer:
public class Solution { public List<Integer> getRow(int rowIndex) { List<Integer> temp = new LinkedList<Integer>(); for(int i=1;i<=rowIndex+1;i++){ List<Integer> result =new LinkedList<Integer>(); result.add(0,1); for(int j=1;j<i-1;j++){ result.add(j,(temp.get(j)+temp.get(j-1))); } if(i>1) result.add(i-1,1); temp=result; } return temp; }}
如果要满足题目use only O(k) extra space要求,则应该将temp删掉,这个时候需要列表的set函数替代add函数,因为add函数添加后其余之后的元素都自动向后移位,而set函数只是将其替换。
Answer:
public class Solution { public List<Integer> getRow(int rowIndex) { List<Integer> result =new LinkedList<Integer>(); for(int i=1;i<=rowIndex+1;i++){ for(int j=1;j<i-1;j++){ result.set(j-1,(result.get(j-1)+result.get(j))); } result.add(0,1); } return result; }}
0 0
- [LeetCode]118. Pascal's Triangle&119. Pascal's Triangle II
- LeetCode-118. Pascal's Triangle,119. Pascal's Triangle II
- 118. Pascal's Triangle && 119. Pascal's Triangle II
- 118. Pascal's Triangle&&119. Pascal's Triangle II
- LeetCode Pascal's Triangle II
- LeetCode: Pascal's Triangle II
- [LeetCode] Pascal's Triangle II
- [Leetcode] Pascal's Triangle II
- 【leetcode】Pascal's Triangle II
- LeetCode - Pascal's Triangle II
- Leetcode: Pascal's Triangle II
- LeetCode-Pascal's Triangle II
- [leetcode] Pascal's Triangle II
- LeetCode - Pascal's Triangle II
- LeetCode | Pascal's Triangle II
- Pascal's Triangle II -leetcode
- Leetcode Pascal's Triangle II
- [LeetCode] Pascal's Triangle II
- Effective C++ 07:为多态基类声明virtual析构函数
- 如何在子模块中获取BuildConfig.DEBUG值
- bzoj 3668: [Noi2014]起床困难综合症 位运算
- Spring进阶之路(5)-Spring创建Bean的三种方式
- C++中随机函数rand()和srand()的用法
- LeetCode-118. Pascal's Triangle,119. Pascal's Triangle II
- contains依赖于equals方法 验证栈是先进后出
- Spring主要模块及其作用
- PAT 1030
- 取石子(一)
- java异常、泛型和反射
- Linux学习笔记:简单了解与设置文件的权限
- 年终总结
- 常见控件的事件监听