iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 11
0

題目:

請看維基百科解釋
https://en.wikipedia.org/wiki/Pascal%27s_triangle
https://leetcode.com/problems/pascals-triangle/

解題思路:

利用2個for迴圈首個數字放入一,中間數值透過第二個for迴圈做相加在最後一個數字填入一,以此循環。

C版本:

int** generate(int numRows, int** columnSizes) {
    int i=0;    
    int j=0;
    if(numRows == 0)
        return 0;
    int ** returnArray = (int **)malloc(sizeof(int *) * numRows);
    *columnSizes = (int *)malloc(sizeof(int)*numRows);

    for(i=0; i<numRows; i++)
    {
        (*columnSizes)[i] = i+1;
         returnArray[i] = (int *)malloc(sizeof(int) * (i+1));
         for(j=0; j<i+1; j++)
         {
            if( (0 == j)  || (i == j) )
                returnArray[i][j] = 1;
            else
                returnArray[i][j] = returnArray[i-1][j-1] + returnArray[i-1][j];
         }
    }
    return returnArray;
}

Javascript版本:

var generate = function(n) {
  var cur = [1,1]
  var result = [1,1,1]
  var temp = []
  temp.push([1],[1,1]);
  if(n==1){return [1]}
  if(n==2){return result}

  for(var i = 2 ; i < n ; i ++){
    var next = [1]      
    for(var j = 0 ; j < cur.length-1  ; j ++){
        next.push(cur[j]+cur[j+1])
    }
    next.push(1)
    temp.push(next)
    cur = next;
  }
  return temp
};

時間複雜度為: O(nxn)

程式Github分享:

https://github.com/SIAOYUCHEN/leetcode

相似主題分享:

https://ithelp.ithome.com.tw/users/20100009/ironman/2500
https://ithelp.ithome.com.tw/users/20113393/ironman/2169
https://ithelp.ithome.com.tw/users/20107480/ironman/2435
https://ithelp.ithome.com.tw/users/20107195/ironman/2382
https://ithelp.ithome.com.tw/users/20119871/ironman/2210
https://ithelp.ithome.com.tw/users/20106426/ironman/2136

本日分享:

One day, perhaps you will find the most touching thing is not that you have finished, but you finally have the courage to start.
有一天,或許你會發現, 最感動的不是你完成了, 而是你終於鼓起勇氣開始。


上一篇
DAY10 Merge Sorted Array
下一篇
DAY12 Maximum Product Subarray
系列文
刷題記錄與人生分享34
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言