杨辉三角 空间复杂度O(k)

今天在leetcode上看到一题如下:

Given an index k, return the kth row of the Pascal's triangle.

For example, given k = 3,
Return [1,3,3,1].

Note:
Could you optimize your algorithm to use only O(k) extra space?

根据所查杨辉三角的资料实现如下:

#include
#include

int caculat(int n, int c){
	int a, b, tmpa, tmpb;
	tmpa = 0;
	tmpb = c;
	a = b = 1;
	while(tmpa < c){
		a = a * (n - tmpa);
		b = b * tmpb;
		tmpa++;
		tmpb--;
	}
	return a/b;
}
void gen_pascal_triangle(int n){
	int a, b, i, *arr;
	arr = (int*) malloc(sizeof(int) * n + 1);
	if(arr == NULL) {
		printf("error, malloc fail\n");
		exit(1);
	}
	for(i = 0; i <= n/2; i++){
		arr[i] = caculat(n, i); 
		arr[n-i] = arr[i];
	}
	if(n % 2 == 0) arr[n/2+1] = caculat(n, n/2+1);
	for(i = 0; i <= n; i++)
		printf("%d,", arr[i]);
	free(arr);
}

int main(void){
	int n;
	scanf("%d", &n);
	gen_pascal_triangle(n);
	return 0;
}
希望看到的各位能给点意见,谢谢啦!

你可能感兴趣的:(leetcode,C,leetcode,算法,Pascals,Triangle)