119. Pascal's Triangle II java solutions
Posted Miller1991
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了119. Pascal's Triangle II java solutions相关的知识,希望对你有一定的参考价值。
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?
1 public class Solution { 2 public List<Integer> getRow(int rowIndex) { 3 Integer[] num = new Integer[rowIndex+1]; 4 num[0] = 1; 5 for(int i = 1; i < num.length; i++){ 6 num[i] = (int)((long)num[i-1]*(rowIndex-i+1)/i);//不加强制转换,乘积大于Integer.MAX_VALUE有溢出 7 } 8 return Arrays.asList(num); 9 } 10 }
1 public class Solution { 2 public List<Integer> getRow(int rowIndex) { 3 List<Integer> list = new ArrayList<Integer>(); 4 list.add(1); 5 for(int i = 1; i < rowIndex + 1; i++){ 6 list.add((int)((long)list.get(i-1)*(rowIndex-i+1)/i)); 7 } 8 return list; 9 } 10 }
根据数学公式:
[C(k,0), C(k,1), ..., C(k, k-1), C(k, k)]
C[k,i] = C[k,i-1]*(k-i+1)/i
以上是关于119. Pascal's Triangle II java solutions的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode_119. Pascal's Triangle II