日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C語言實現動態開辟存儲楊輝三角_C 語言

作者:寄一片海給你 ? 更新時間: 2022-05-14 編程語言

問題引入

楊輝三角相必大家并不陌生,第1行有1列、第二行有2列…第n行有n列,且每行行首和行尾的值都為1,其余的值為上一行兩數相加

我們在C語言階段,第一次碰到的楊輝三角應該都是用常規的二維數組存儲,可以觀察到,用綠色填充的空間都是沒有被利用的。

存儲1行 ??????????????????浪費0個

存儲2行 ??????????????????浪費1個

存儲3行 ??????????????????浪費3個?

存儲4行 ??????????????????浪費6個

????????????????.

????????????????.

????????????????.

存儲n行 ??????????????浪費n*(n+1)/2-n個

解決方法

這樣極大浪費空間資源,今天我們就來試試動態開辟存儲楊輝三角,可以靈活的開辟空間,充分的利用空間。

思路分析

首先用指針pp維護動態開辟的int*類型的指針,再通過int*類型的指針去維護動態開辟的int型數據存儲楊輝三角

C代碼實現

#include 
#include 

void PrintFree(int** pp, int numrows)
{	
	//打印
	for (int i = 0; i < numrows; i++)
	{	
		for (int k = 0; k < numrows  -  i; k++)
		{
			printf("   ");
		}
		for (int j = 0; j <= i; j++)
		{
			printf("%4d", pp[i][j]);	//可以根據打印的行數適當調整右對齊
			printf("   ");
		}
		printf("\n");
	}
}
	//清理malloc出來的空間
	for (int i = 0; i < numrows; i++)
	{
		free(pp[i]);
		pp[i] = NULL;
	}
}

int main()
{	
	//楊輝三角的行數
	int numrows;
	scanf("%d", &numrows);
	//開辟numrows個int*類型的指針用來維護int型的數據
	int** pp = (int**)malloc(sizeof(int*) * numrows);
	for (int i = 0; i < numrows; i++)
	{	
		//int型數據個數隨著行數的增加而增加
		pp[i] = (int*)malloc(sizeof(int) * (i + 1));
	}
	for (int i = 0; i < numrows; i++)
	{
		for (int j = 0; j <= i; j++)
		{	
			//每行的行首和行尾都是1
			if (j == 0 || i == j)
			{
				pp[i][j] = 1;     //	等價于 *(*(pp+i)+j)
			}
			//其余的就是上一行的兩個數據相加
			else
			{
				pp[i][j] = pp[i - 1][j - 1] + pp[i - 1][j];
			}
		}
	}
	PrintFree(pp, numrows);

	return 0;
}

大家可以根據需要打印的行數大小在上面的打印函數適當調整

C++實現

用C++就非常方便了,STL中的vector就可以很方便的解決

#include 
#include 
using namespace std;

//打印函數
void Print(vector> vv, int numrows)
{
	for (int i = 0; i < numrows; i++)
	{
		for (int j = 0; j <= i; j++)
		{
			cout << vv[i][j] << "   ";
		}
		cout << endl;
	}
}
int main()
{	
	int numrows;
	cin >> numrows;
	vector> vv;
	for (int i = 0; i < numrows; i++)
	{	
		//每次開i+1個vector
		vv.resize(i + 1);
		//每次開i+1個int
		vv[i].resize(i + 1);
	}
	for (int i = 0; i < numrows; i++)
	{
		for (int j = 0; j <= i; j++)
		{
			if (j == 0 || i == j)
			{
				vv[i][j] = 1;
			}
			else
			{
				vv[i][j] = vv[i - 1][j - 1] + vv[i - 1][j];
			}
		}
	}
	Print(vv, numrows);

	return 0;

}

以上就是通過動態開辟的楊輝三角了

原文鏈接:https://blog.csdn.net/weixin_46016019/article/details/123374503

欄目分類
最近更新