[LeetCode64]Pascal's Triangle

来源:互联网 发布:php include 来源 编辑:程序博客网 时间:2024/05/16 02:15

Given numRows, generate the first numRows of Pascal's triangle.

For example, given numRows = 5,
Return

[     [1],    [1,1],   [1,2,1],  [1,3,3,1], [1,4,6,4,1]]
Analysis:

根据帕斯卡三角的定义

Java

public ArrayList<ArrayList<Integer>> generate(int numRows) {        // IMPORTANT: Please reset any member data you declared, as        // the same Solution instance will be reused for each test case.        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();        for(int i=0; i<numRows; i++){        ArrayList<Integer> temp = new ArrayList<Integer>();        temp.add(1);        if(i>0){        for(int j=0; j<result.get(i-1).size()-1;j++)        temp.add(result.get(i-1).get(j)+result.get(i-1).get(j+1));        temp.add(1);        }        result.add(temp);                }        return result;    }

c++

vector<vector<int> > generate(int numRows) {        vector<vector<int>> result;        if(numRows==0) return result;    vector<int> tem;    tem.push_back(1);    result.push_back(tem);    if(numRows==1) return result;    tem.push_back(1);    result.push_back(tem);    if(numRows==2) return result;    for(int i=2;i<numRows;i++){        vector<int> solu(i+1,1);        for(int j=1;j<i;j++){            solu[j] = result[i-1][j-1]+result[i-1][j];        }        result.push_back(solu);    }    return result;    }




0 0
原创粉丝点击