【項目 2-楊輝三角】編寫程序,打印出以下形式的揚輝三角形。楊輝三角是一個由數字排列成的三角形數表,一般形式如下:
??????????? 1
??????? 1 1
?????? 1 2 1
????? 1 3 3 1
???? 1 4 6 4 1
??? 1 5 10 10 5 1
?? ......................................................
楊輝三角最本質的特征是,它的兩條斜邊都是由數字1組成的,而其余的數則是等于它肩上的兩個數之和。?? 一、使用一維數組:據“F(x)=F(x)+F(x-1)”計算。此算法比較快,但數據受數組大小限制。可以將楊輝三角形的值放在一個方形矩陣的下半三角中,如果需打印 7 行楊輝三角形,應該定義等于或大于 7X7 的方形矩陣,只是矩陣的上半部和其余部分并不使用。
### 楊輝三角形具有如下特點:
- 第 0 列和對角線上的元素都為 1。
- 除第 0 列和對角線上的元素以外,其它元素的值均為前一行上的同列元素和前一列元素之和。
### 代碼:
~~~
// 楊輝三角形算法.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
int factorial(int n);
int combine(int a, int b);
void space(int t, int line);
int _tmain(int argc, _TCHAR* argv[])
{
int line;
cout<<"Please Input the line number :";
cin>>line;
while(line!=-1){
for( int i=1;i<line;i++){
space(i,line);
for(int j =0; j<i; j++){
cout << combine(j, i-1)<<" ";
}
cout<<endl;
}
cout <<endl<<" Please Input the line number: (enter -1 to quit) ";
cin>>line;
}
return 0;
}
int factorial(int n){
int i =1;
int product =1;
while(i<=n){
product =product*i;
i++;
}
return product;
}
int combine(int a, int b){
int result;
if( a==0||b==0)
return 1;
else
result = factorial(b)/(factorial(a)*factorial(b-a));
return result;
}
void space ( int t, int line){
for(int p =1; p<=(line-t);p++)
cout <<" ";
}
~~~
### 輸出結果:

**轉載請注明出處:http://blog.csdn.net/utimes/article/details/8453961**
- 前言
- 螺旋矩陣、螺旋隊列算法
- 程序算法藝術與實踐:稀爾排序、冒泡排序和快速排序
- Josephu 問題:數組實現和鏈表實現
- 楊輝三角形算法
- 位圖排序
- 堆排序的實現
- Juggling算法
- 【編程珠璣】排序與位向量
- 取樣問題
- 變位詞實現
- 隨機順序的隨機整數
- 插入排序
- 二分搜索
- 產生不重復的隨機數
- 約瑟夫環解法
- 快速排序
- 旋轉交換或向量旋轉
- 塊變換(字符反轉)
- 如何優化程序打印出小于100000的素數
- 基本的排序算法原理與實現
- 利用馬爾可夫鏈生成隨機文本
- 字典樹,后綴樹
- B-和B+樹
- 程序算法藝術與實踐引導
- 程序算法藝術與實踐:基礎知識之有關算法的基本概念
- 程序算法藝術與實踐:經典排序算法之桶排序
- 程序算法藝術與實踐:基礎知識之函數的漸近的界
- 程序算法藝術與實踐:遞歸策略之矩陣乘法問題
- 程序算法藝術與實踐:遞歸策略之Fibonacci數列
- 程序算法藝術與實踐:遞歸策略基本的思想
- 程序算法藝術與實踐:經典排序算法之插入排序
- 程序算法藝術與實踐:遞歸策略之遞歸,循環與迭代