首页 > 代码库 > Pascal's Triangle Pascal's Triangle||

Pascal's Triangle Pascal's Triangle||

Pascal‘s Triangle:

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]]

Pascal‘s Triangle||:

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?

Pascal‘s triangle.

public class Solution {	public List<List<Integer>> generate(int numRows) {	    if(numRows == 0){			return new ArrayList<List<Integer>>();		}		List<List<Integer>> ans = new ArrayList<List<Integer>>();		ans.add(new ArrayList<Integer>(Arrays.asList(1)));		for(int i=1;i<numRows;i++){			List<Integer> list = new ArrayList<Integer>();			for(int j=0;j<=i;j++){				if(j==0||j==i){					list.add(1);					continue;				}				list.add(ans.get(i-1).get(j-1)+ans.get(i-1).get(j));			}			ans.add(list);		}		return ans;	}}

Pascal‘s Triangle||:

public class Solution {    	public List<Integer> getRow(int rowIndex) {		List<Integer> ans = new ArrayList<Integer>();		for(int i=0;i<=rowIndex;i++){			List<Integer> temp = new ArrayList<Integer>();			for(int j=0;j<=i;j++){				if(j==0||j==i){					temp.add(1);					continue;				}				temp.add(ans.get(j)+ans.get(j-1));			}			ans = new ArrayList<Integer>(temp);		}		return ans;	}}


其实这些基本处理就是学习C语言时的杨辉三角。

 

 

Pascal's Triangle Pascal's Triangle||