LeetCode119:楊輝三角II
阿新 • • 發佈:2018-12-15
解析:
此題和之前118類似,只是該題只需要輸出第K行即可,因此不需要儲存所有行的元素。不再需要定義一個二維陣列,只需要定義兩個一維陣列,用來儲存本行和上一行的值就可以了。
程式碼 :
vector<int> getRow(int rowIndex) { vector<int> result; if (rowIndex < 0)//特殊的兩種情況 return result; result.push_back(1); if (rowIndex == 0) return result; vector<int> lastLine = result; for (int i = 1; i <= rowIndex; i++) { result = vector<int>(i+1, 1); for (int j = 1; j < i; j++)//每行不超過i+1個元素,每行最後一個元素為1 { result[j] = lastLine[j - 1] + lastLine[j]; } lastLine = result;//更新上一行元素 } return result; }