zoukankan      html  css  js  c++  java
  • [Leetcode]-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]
    ]

    题目:依据numRows生成帕斯卡三角形。帕斯卡三角形原理点击这里
    思路:帕斯卡三角形的每行首、位元素都为1。其它的元素为上一行两个元素之和:

    if(0 == j || i == j)   r[i][j] = 1;
    else                   r[i][j] = r[i-1][j-1] + r[i-1][j];

    注意事项:
    1、numRows为0的时候返回0
    2、一定要自己分配内存空间

    #include <stdlib.h>
    #include <stdio.h>
    
    /**
     * Return an array of arrays of size *returnSize.
     * The sizes of the arrays are returned as *columnSizes array.
     * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
     */
    int** generate(int numRows, int** columnSizes, int* returnSize) {
    
        if(0 == numRows) return 0;
        *returnSize = numRows  ; 
        int i = 0, j = 0;
        int** r = (int**)malloc(sizeof(int*) * numRows);
        //int*cn    = (int*)malloc(sizeof(int) * numRows);
        *columnSizes = (int*)malloc(sizeof(int) * numRows);
        //*columnSizes = cn;
        for(i=0;i<numRows;i++)
        {
            //cn[i] = i + 1;
            columnSizes[0][i] = i + 1 ;
            r[i]  = (int*)malloc(sizeof(int)*(i+1));
        }
    
        for(i=0;i<numRows;i++)
        {
            for(j=0;j<i+1;j++)
            {
                if(0 == j || i == j) r[i][j] = 1;
                else r[i][j] = r[i-1][j-1] + r[i-1][j];
            }
        }
        return r;
    }
    
    int main()
    {   
        int num = 3 ;
        int *columnSizes ;//每一行有几个元素
        int returnSize = 0;
        int **r = generate(num,&columnSizes,&returnSize);
        int i = 0;
        int j = 0;
        printf("toal element size is : %d
    ",returnSize);
        for(i=0;i<num;i++)
        {
            printf("%d row have %d element 
    ",i,columnSizes[i]);
        }
    
        for(i=0;i<num;i++)
        {
            for(j=0;j<i+1;j++)
                printf("r[%d][%d]  = %d
    ",i,j,r[i][j]);
    
            printf("
    ");
        }
    }
    
  • 相关阅读:
    8.22
    webstrom安装流程
    8.21
    8.20
    8.20学习笔记
    使用WebClient异步获取http资源
    导航栏,可直接使用
    asp.net mvc5实现单点登录
    使用C#调用Word的接口生成doc文件与html文件
    下载网页并保存
  • 原文地址:https://www.cnblogs.com/yangykaifa/p/7294929.html
Copyright © 2011-2022 走看看