Pascal's Triangle帕斯卡三角形算法

题目 Pascal's triangle 

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]
]

分析:

  1. 非递归实现,类似于用数组实现。
  2. 递归实现。
class Solution {
public:
    vector > generate(int numRows) {
        vector> result;
        if(numRows < 1){
            return result;
        }
        vector line;
        line.push_back(1);
        result.push_back(line);
        if(numRows == 1){
            return result;
        }
        for(int i = 2; i <= numRows; i++){
            line.clear();
            line.push_back(1);
            for(int j = 0; j < i - 2; j++){
                line.push_back(result[i - 2][j] + result[i - 2][j + 1]);
            }
            line.push_back(1);
            result.push_back(line);
        }
        return result;
    }
};
class Solution {
public:
	vector > generate(int numRows) {
		vector v, temp;
		vector >vv;

		if (numRows == 1)
		{
			v.push_back(1);
			vv.push_back(v);
		}
		else if (numRows > 1)
		{
			vv = generate(numRows-1); //拷贝构造numRows-1时的vv给当前的vv
			temp = vv.back();
			//vv.clear(); //打开该屏蔽只输出该行
			v.push_back(1);
			for (int i = 1; i < numRows - 1; i++)
			{
				v.push_back(temp[i-1]+temp[i]);
			}
			v.push_back(1);
			vv.push_back(v);
		}
		return vv;
	}
};


你可能感兴趣的:(leetcode)