LeetCode简单题:119. 杨辉三角 II(Python,C++,Java)

一.解法

https://leetcode-cn.com/problems/pascals-triangle-ii/
要点:递归
大致同118题一样,不过118题我用循环迭代做,这题不需要保存我直接用递归做
Python,C++,Java都用了相同的递归方法,思路是找到杨辉三角的上一层后,这一层先添加1,再for i in range(0,rowIndex-1)添加上一层的位置i和位置i+1的和,最后再添加1

二.Python实现

class Solution:
    def getRow(self, rowIndex: int) -> List[int]:
        answer=[]
        temp=[]
        if rowIndex==0:
            answer.append(1)
            return answer
        answer.append(1)
        temp=self.getRow(rowIndex-1)
        for i in range(0,rowIndex-1):
            answer.append(temp[i]+temp[i+1])
        answer.append(1)
        return answer

三.C++实现

class Solution {
public:
    vector getRow(int rowIndex) {
        vector answer;
        vector temp;
        if(rowIndex==0) {answer.push_back(1);return answer;}
        answer.push_back(1);
        temp=getRow(rowIndex-1);
        for(int i=0;i

四.java实现

class Solution {
    public List getRow(int rowIndex) {
        List answer=new ArrayList<>();
        List temp=new ArrayList<>();
        if(rowIndex==0) {answer.add(1);return answer;}
        answer.add(1);
        temp=getRow(rowIndex-1);
        for(int i=0;i

你可能感兴趣的:(LeetCode简单题:119. 杨辉三角 II(Python,C++,Java))