国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 學(xué)院 > 開(kāi)發(fā)設(shè)計(jì) > 正文

leecode 解題總結(jié):118. Pascal's Triangle

2019-11-08 20:08:30
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友
#include <iostream>#include <stdio.h>#include <vector>using namespace std;/*問(wèn)題: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]]分析:題目提供一個(gè)行數(shù),然后需要你編寫出楊輝三角。楊輝三角實(shí)際是有二項(xiàng)式系數(shù)列表組成。(a+b)^2=a^2 + 2*a*b + b^2(a+b)^n=C(n,k) * a^(n-k) * b^k 累加求和,其中k從0到n以n=4為例,系數(shù)為:1 , 4 , 6 , 4, 1。此時(shí)對(duì)應(yīng)的numRows=5,所以numRows - 1 = nC(n,0)=C(n,n)=1,以n=5為例,C(5,0)=1,C(5,1)根據(jù)傳入的函數(shù)計(jì)算即可。如果每次根據(jù)組合公式,計(jì)算量很大C(n,k) = n! / ( (k!) * (n-k)! )觀察發(fā)現(xiàn):楊輝三角從第三行開(kāi)始,上一行和下一行之間存在遞推關(guān)系,下一行處第一個(gè)數(shù)字和最后一個(gè)數(shù)字均為1外,設(shè)上一行數(shù)組為A,下一行數(shù)組為B,則有B[i] = A[i-1] + A[i],其中i >= 2, i <= A.len 輸入:015輸出:no result11,1,1,1,2,1,1,3,3,1,1,4,6,4,1關(guān)鍵:1 觀察發(fā)現(xiàn):楊輝三角從第三行開(kāi)始,上一行和下一行之間存在遞推關(guān)系,下一行處第一個(gè)數(shù)字和最后一個(gè)數(shù)字均為1外,設(shè)上一行數(shù)組為A,下一行數(shù)組為B,則有B[i] = A[i-1] + A[i],其中i >= 2, i <= A.len 采用遞推來(lái)做2 (a+b)^n=C(n,k) * a^(n-k) * b^k 累加求和,其中k從0到nC(n,k) = n! / ( (k!) * (n-k)! )*/class Solution {public:    vector<vector<int>> generate(int numRows) {		vector<vector<int>> results;		//numRows至少為1,		if(numRows < 1)		{			return results;		}		//初始化第一行和第二行,從第三行開(kāi)始進(jìn)行地推        for(int i = 1; i <= numRows ; i++)		{			vector<int> result(i , 1);			//開(kāi)始遞推,公式為:			if(i > 2)			{				//這里i-1取不到				for(int j = 1 ; j < i - 1; j++)				{					result.at(j) = results.at(i-2).at(j-1) + results.at(i-2).at(j);				}				results.push_back(result);			}			else			{				results.push_back(result);			}		}		return results;    }};void PRint(vector<vector<int> >& result){	if(result.empty())	{		cout << "no result" << endl;		return;	}	int size = result.size();	int len;	for(int i = 0 ; i < size ; i++)	{		len = result.at(i).size();		for(int j = 0 ; j < len ; j++)		{			cout << result.at(i).at(j) << "," ;		}		cout << endl;	}}void process(){	 int num;	 Solution solution;	 vector<vector<int> > result;	 while(cin >> num )	 {		 result = solution.generate(num);		 print(result);	 }}int main(int argc , char* argv[]){	process();	getchar();	return 0;}
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 读书| 宝应县| 闽侯县| 常熟市| 遵义县| 扎赉特旗| 三都| 栾川县| 灯塔市| 陆丰市| 井陉县| 馆陶县| 光泽县| 新巴尔虎左旗| 陇西县| 朝阳县| 临澧县| 清远市| 临沂市| 周宁县| 迭部县| 昌乐县| 岱山县| 通州区| 盐津县| 兴义市| 张家港市| 新巴尔虎左旗| 江达县| 扎赉特旗| 宾阳县| 天全县| 威宁| 恭城| 德化县| 偃师市| 栾城县| 岳阳市| 岫岩| 柳江县| 沙雅县|