陣列和字串//楊輝三角 II
阿新 • • 發佈:2018-12-26
給定一個非負索引 k,其中 k ≤ 33,返回楊輝三角的第 k 行。
在楊輝三角中,每個數是它左上方和右上方的數的和。
示例:
輸入: 3 輸出: [1,3,3,1]
進階:
你可以優化你的演算法到 O(k) 空間複雜度嗎?
class Solution { public List<Integer> getRow(int rowIndex) { List<Integer> list = new ArrayList<Integer>(); for(int i = 0; i <= rowIndex; i++){ list.add(1); for(int j = i-1; j >= 1; j--){ list.set(j,list.get(j)+list.get(j-1)); } } return list; } }
class Solution { public: vector<int> getRow(int rowIndex) { vector<int> out; if(rowIndex < 0) return out; out.assign(rowIndex+1,0); for(int i = 0; i <= rowIndex; i++){ if(i == 0){ out[0] = 1; continue; } for(int j = rowIndex; j >= 1; j--){ out[j] = out[j] + out[j-1]; } } return out; } };