题目链接:https://leetcode.com/problems/pascals-triangle-ii/
题目:
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?
思路:
要求空间复杂度为O(k),其实只需要记录前一行的结果就可以了。
算法:
-
public List<Integer> getRow(int rowIndex) {
-
List<Integer> pre;
-
List<Integer> cur=null;
-
for (int i = 1; i <= rowIndex + 1; i++) {
-
pre = cur;
-
cur = new ArrayList<Integer>();
-
if (i == 1) {
-
cur.add(1);
-
} else if (i == 2) {
-
cur.add(1);
-
cur.add(1);
-
} else if (i > 2) {
-
cur.add(1);
-
for (int j = 0; j < pre.size() - 1; j++) {
-
cur.add(pre.get(j) + pre.get(j + 1));
-
}
-
cur.add(1);
-
}
-
}
-
return cur;
-
}
【Leetcode】Pascal's Triangle II
原文:http://blog.csdn.net/yeqiuzs/article/details/51628548