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)的额外空间,求第K行帕斯卡三角形的数
C++(0ms):
1 class Solution { 2 public: 3 vector<int> getRow(int rowIndex) { 4 vector<int> res(rowIndex+1,0) ; 5 res[0] = 1 ; 6 for(int i = 1 ; i < rowIndex+1 ; i++){ 7 for(int j = i ; j >=1 ; j--){ 8 res[j] += res[j-1] ; 9 } 10 } 11 return res ; 12 } 13 };
java(2ms):
1 class Solution { 2 public List<Integer> getRow(int rowIndex) { 3 List<Integer> list = new ArrayList<Integer>(rowIndex+1) ; 4 if (rowIndex < 0) 5 return list ; 6 7 for(int i = 0 ; i <= rowIndex ; i++){ 8 list.add(1) ; 9 for(int j = i-1 ; j >= 1 ; j--){ 10 list.set(j , list.get(j) + list.get(j-1)) ; 11 } 12 } 13 return list ; 14 } 15 }