Leet Code OJ 119. Pascal's Triangle II [Difficulty: Easy]
生活随笔
收集整理的這篇文章主要介紹了
Leet Code OJ 119. Pascal's Triangle II [Difficulty: Easy]
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目:
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?
翻譯:
給定一個下標k,返回第k行的楊輝三角。
例如給定k=3,返回[1,3,3,1]。
提示:你可以優化你的算法,讓它只使用O(k)的額外空間嗎?
分析:
如果采用Leet Code OJ 118. Pascal’s Triangle中的方案來做這道題,也就是使用2個Integer數組進行存儲,空間復雜度是O(2k),實際是等價于O(k)的,但是我們考慮一下能否再優化一些。下面的方案去掉lastLine這個數組,采用2個整數代替,空間復雜度為O(k+2),略優于之前方案。
Java版代碼:
public class Solution {public List<Integer> getRow(int rowIndex) {List<Integer> line=new ArrayList<>();line.add(1);if(rowIndex==0){return line;}for(int i=1;i<=rowIndex;i++){int lastNum=1;int currentNum=1;for(int j=1;j<i;j++){currentNum=line.get(j);line.set(j,lastNum+currentNum);lastNum=currentNum;}line.add(1);}return line;} }總結
以上是生活随笔為你收集整理的Leet Code OJ 119. Pascal's Triangle II [Difficulty: Easy]的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Leet Code OJ 118. Pa
- 下一篇: Leet Code OJ 2. Add