标签:leetcode algorithm pascal 杨辉三角
杨辉三角,分别求前n行和第n行。
【求杨辉三角前n行】
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] ]基础题,直接看代码,注意边界。
public class Solution { public List<List<Integer>> generate1(int numRows) { List<List<Integer>> ret = new ArrayList<List<Integer>>(); if (numRows == 0) return ret; List<Integer> list0 = new ArrayList<Integer>(); list0.add(1); ret.add(list0); for (int i = 2; i <= numRows; i++) { List<Integer> list = new ArrayList<Integer>(); list.add(1); List<Integer> pre = ret.get(ret.size()-1); for (int j = 1; j < i-1; j++) { list.add(pre.get(j-1) + pre.get(j)); } list.add(1); ret.add(list); } return ret; } // another style public List<List<Integer>> generate(int numRows) { List<List<Integer>> ret = new ArrayList<List<Integer>>(); for (int i = 0; i < numRows; i++) { List<Integer> list = new ArrayList<Integer>(); if (i == 0) { list.add(1); } else { List<Integer> pre = ret.get(ret.size()-1); for (int j = 0; j <= i; j++) { if (j == 0 || j == i) { list.add(1); } else { list.add(pre.get(j-1) + pre.get(j)); } } } ret.add(list); } return ret; } }
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?
用O(k)的空间记录前一行就行了。
public class Solution { public List<Integer> getRow(int rowIndex) { List<Integer> list = new ArrayList<Integer>(); list.add(1); List<Integer> pre = new ArrayList<Integer>(list); for (int i = 1; i <= rowIndex; i++) { list.clear(); list.add(1); for (int j = 1; j < pre.size(); j++) { list.add(pre.get(j) + pre.get(j-1)); } list.add(1); pre.clear(); pre.addAll(list); } return list; } }
标签:leetcode algorithm pascal 杨辉三角
原文地址:http://blog.csdn.net/ljiabin/article/details/40304037