119.Pascal's Triangle II

題目連接數組

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

法一:這裏用一個list數組實現,就會致使全部數據存在一個list中,沒法分辨的問題,因此後來要新開一個list從前面的list中抽取出最後的結果數據。空間複雜度不是o(k),代碼以下(耗時3ms):spa

 1     public List<Integer> getRow(int rowIndex) {
 2         List<Integer> list = new ArrayList<Integer>();
 3         rowIndex++;
 4         //用單list,將全部行的全部數據都存在一個list中,沒有分辨
 5         for(int i = 1; i <= rowIndex; i++) {
 6             for(int j = 0; j < i; j++) {
 7                 if(j == 0 || j == i - 1) {
 8                     list.add(1);
 9                 }
10                 else {
11                     list.add(list.get(list.size()-i) + list.get(list.size()-i+1));
12                 }
13             }
14         }
15         //從上面獲得的list中,抽取最後一行的數據
16         List<Integer> res = new ArrayList<Integer>();
17         for(int i = list.size() - rowIndex; i < list.size(); i++) {
18             res.add(list.get(i));
19         }
20         return res;
21     }
View Code

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

 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中的數據就新加一個,此外別無添加,因此list的數據個數老是保持這次add後的恆定值
 6             //而這裏的add其實就是將當前層的最後一個數置1
 7             list.add(1);
 8             for(int j = i - 1; j > 0; j--) {
 9                 //從當前層的倒數第二個數開始往前到第二個數,進行遍歷更新
10                 list.set(j, list.get(j - 1) + list.get(j));
11             }
12         }
13         return list;
14     }
View Code

模擬代碼以下:blog

當rowIndex=4時:ip

i=0,list{1};leetcode

i=1,list{1,1};get

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

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

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}

相關文章
相關標籤/搜索