1. 程式人生 > >119.Pascal's Triangle II

119.Pascal's Triangle II

color img des close 實現 rip com lap pan

題目鏈接:https://leetcode.com/problems/pascals-triangle-ii/description/

題目大意:給出第幾行,返回楊輝三角裏的該行數據。要求空間復雜度o(k)

法一:這裏用一個list數組實現,還是兩層for循環,但是空間復雜度不是o(k),代碼如下(耗時3ms):

技術分享
 1     public List<Integer> getRow(int rowIndex) {
 2         List<Integer> list = new ArrayList<Integer>();
 3         rowIndex++;
4 for(int i = 1; i <= rowIndex; i++) { 5 for(int j = 0; j < i; j++) { 6 if(j == 0 || j == i - 1) { 7 list.add(1); 8 } 9 else { 10 list.add(list.get(list.size()-i) + list.get(list.size()-i+1));
11 } 12 } 13 } 14 List<Integer> res = new ArrayList<Integer>(); 15 for(int i = list.size() - rowIndex; i < list.size(); i++) { 16 res.add(list.get(i)); 17 } 18 return res; 19 }
View Code

法二(借鑒):用數組值疊加的方式,從後往前疊加,空間復雜度達到o(k),list.set(2,i)表示把list中第2位的數值替換成i。代碼如下(耗時2ms):

技術分享
 1     public List<Integer> getRow(int rowIndex) {
 2         List<Integer> list = new ArrayList<Integer>();
 3         rowIndex++;
 4         for(int i = 0; i < rowIndex; i++) {
 5             list.add(1);
 6             for(int j = i - 1; j > 0; j--) {
 7                 list.set(j, list.get(j - 1) + list.get(j));
 8             }
 9         }
10         return list;
11     }
View Code

模擬代碼如下:

當rowIndex=4時:

i=0,list{1};

i=1,list{1,1};

i=2,list{1,1,1}->list{1,2,1};

i=3,list{1,2,1,1}->list{1,2,3,1}->list{1,3,3,1};

i=4,list{1,3,3,1,1}->list{1,3,3,4,1}->list{1,3,6,4,1}->list{1,4,6,4,1}

119.Pascal's Triangle II