[leetcode]Pascal's Triangle II

来源:互联网 发布:vb getvalue 编辑:程序博客网 时间:2024/05/04 16:37

题目描述如下:

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?

杨辉三角的变形,Note说要用O(k)的空间,想到可以用递归完成。

其他也没有什么难度,代码如下:

public class Solution {    public List<Integer> getRow(int rowIndex) {        List<Integer> list = new ArrayList<Integer>();        int i ;        if(rowIndex == 0) {            list.add(1);            return list;        }else{            List<Integer> tmplist =  getRow(rowIndex - 1);            for(i = 0; i < rowIndex + 1; i++){                if(i == 0 || i == rowIndex)                    list.add(1);                else{                    list.add(tmplist.get(i - 1) + tmplist.get(i));                }            }            return list;        }    }}

题目链接:https://leetcode.com/problems/pascals-triangle-ii/

0 0
原创粉丝点击