【LeetCode】Pascal's Triangle II

Pascal's Triangle II 
Accepted: 11888 Total Submissions: 39509 My Submissions
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?
【解题思路】
1、参照Pascal's Triangle,算出所有的list,直接get(rowIndex)
2、如果是空间限制,只能声明k长度的list,依次计算。具体实现是这样的:
1)、初始化一个list
2)、每个列表的第一个值是1
3)、针对每个列表,长度应该是当前rowIndex+1
4)、那么列表元素值为当前值+前一个值,其实就是递推。
5)、循环刚开始,前一个值为1,以后前一个值需要记录。
6)、最后别忘了最后一个值是1
事实证明,限制空间,时间就会变长。

1、Java AC 360ms

public class Solution {
    public ArrayList getRow(int rowIndex) {
        if(rowIndex < 0){
            return new ArrayList();
        }
        return generate(rowIndex+1).get(rowIndex);
    }
    public ArrayList> generate(int numRows) {
        ArrayList> list = new ArrayList>();
        if(numRows <= 0){
            return list;
        }
        ArrayList firstList = new ArrayList();
        firstList.add(1);
        list.add(firstList);
        for(int i = 1; i < numRows; i++){
            ArrayList secList = new ArrayList();
            ArrayList tempList = list.get(i-1);
            int size = tempList.size();
            secList.add(1);
            for(int j = 1; j < size; j++){
                secList.add(tempList.get(j-1) + tempList.get(j));
            }
            secList.add(1);
            list.add(secList);
        }
        return list;
    }
}
1、Python AC 136ms

class Solution:
    # @return a list of integers
    def getRow(self, rowIndex):
        return self.generate(rowIndex+1)[rowIndex]

    def generate(self, numRows):
        list = []
        if numRows <= 0:
            return []
        list.append([1])
        for i in range(1, numRows):
            tempList = list[i-1]
            rowList = []
            rowList.append(1)
            for j in range(1,len(tempList)):
                rowList.append(tempList[j-1] + tempList[j])
            rowList.append(1)
            list.append(rowList)
        return list
		
		
2、Java AC 392MS

public class Solution {
    public List getRow(int rowIndex) {
		List list = new ArrayList();
		list.add(1);
		for (int i = 1; i < rowIndex + 1; i++) {
			int curNum = 1;
			for (int j = 1; j < i; j++) {
				int temp = curNum;
				curNum = list.get(j);
				list.set(j, curNum + temp);
			}
			list.add(1);
		}
		return list;
	}

}
2、Python AC 152MS

class Solution:
    # @return a list of integers
    def getRow(self, rowIndex):
        list = [1]
        for i in range(1,rowIndex+1):
            curNum = 1
            for j in range(1, i):
                temp = curNum
                curNum = list[j]
                list[j] = temp + list[j]
            list.append(1)
        return list
		
		


你可能感兴趣的:(算法,LeetCode,python,LeetCode解题报告)