Leetcode刷题记—— 118. 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]
]

Subscribe to see which companies asked this question

即给定一个整数numRows,输出杨辉三角前numRows行即可。

二、解题思路:

非常简单的题,只用知道杨辉三角的定义及规律即可。。。

三、源码:

import java.util.ArrayList;
import java.util.List;

public class Solution
{
    public List> generate(int numRows) 
    {
        List> result = new ArrayList>();
        for (int i = 0; i < numRows; i++)
        {
        	List a = new ArrayList();
        	//if (i == 0) {return result;}
            if (i == 0) {a.add(1); result.add(a);}
        	else
        	{
        		a.add(1);
        		for (int j = 1; j < i; j++)
        		{
        			a.add(result.get(i - 1).get(j - 1) + result.get(i - 1).get(j));
        			
        		}
        		a.add(1);
        		result.add(a);
        	}
        }
        return result;
    }
    public static void main(String args[])
    {
    	
    	int target = 5;
    	Solution solution = new Solution();
    	System.out.println(solution.generate(target));
    
    }
}


你可能感兴趣的:(刷刷刷题,leetcode,java)