Pascal's Triangle II 求Pascal三角的某一行 @LeetCode
来源:互联网 发布:sqlserver误删数据库 编辑:程序博客网 时间:2024/05/21 06:34
题目:
求Pascal三角的某一行
是前一题的follow up
http://blog.csdn.net/fightforyourdream/article/details/12867855
思路:
用了笨方法,基于前一题的结果,来取值。应该有用数学公式直接计算出来的办法。
package Level2;import java.io.ObjectInputStream.GetField;import java.util.ArrayList;/** * 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? */public class S119 {public static void main(String[] args) {System.out.println(getRow(0));}public static ArrayList<Integer> getRow(int rowIndex) {ArrayList<ArrayList<Integer>> list = generate(rowIndex+1);return list.size()==0 ? null : list.get(rowIndex); }private static ArrayList<ArrayList<Integer>> generate(int numRows) {ArrayList<ArrayList<Integer>> ret = new ArrayList<ArrayList<Integer>>();int i, j;// i用来走列 for(i=0; i<numRows; i++){ ArrayList<Integer> list = new ArrayList<Integer>(); // j用来走行,先走前半行 for(j=0; j<=i/2; j++){ if(j == 0){// 对首位特殊处理 list.add(1); }else if(i>0){// 累加前面结果 list.add(ret.get(i-1).get(j-1)+ret.get(i-1).get(j)); } } // i再走后半行 for(; j<=i; j++){ if(j == i){// 对末位特殊处理 list.add(1); }else if(i>0){// 累加前面结果 list.add(ret.get(i-1).get(j-1)+ret.get(i-1).get(j)); } } ret.add(list); } return ret; }}
public class Solution { public ArrayList<Integer> getRow(int rowIndex) { ArrayList<Integer> old = new ArrayList<Integer>(); ArrayList<Integer> cur = new ArrayList<Integer>(); int i, j; for(i=0; i<=rowIndex; i++){ for(j=0; j<i+1; j++){ if(j == 0){ cur.add(1); }else if(j == i){ cur.add(1); }else{ cur.add(old.get(j-1)+old.get(j)); } } old.clear(); old.addAll(cur); cur.clear(); } return old; }}
- Pascal's Triangle II 求Pascal三角的某一行 @LeetCode
- 写出杨辉三角的某一行 Pascal's Triangle II
- Pascal's Triangle 打印Pascal三角 @LeetCode
- 【Leetcode】Pascal's Triangle II (Pascal)
- 【LeetCode】Pascal's Triangle II (杨辉三角)
- [LeetCode]-Pascal's Triangle I&II 杨辉三角问题
- LeetCode 119. Pascal's Triangle II(帕斯卡三角)
- [leetcode, python] 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 打印Pascal三角 @LeetCode
- Section 2: Console Tab : Using Commandline API in Firebug
- Ubuntu命令大全
- 调试小程序
- 【玩转cocos2d-x之十二】plist解析工具:Anti_TexturePacker
- Pascal's Triangle II 求Pascal三角的某一行 @LeetCode
- iscsi
- JSP 四个作用域及九个内置对象
- Section 3: Console Tab : Logging, Profiling and CommandLine (Part I)
- Section 3: Console Tab : Logging, Profiling and CommandLine (Part II)
- 天空一声巨响,GPFS闪亮登场 (GPFS vs HDFS)
- Section 4 : HTML Tab – Examples
- Section 5 : HTML Tab – All about HTML tab
- Section 6: Script Tab : Javascript Debugging