1. 程式人生 > >[leetcode]118,119PascalsTriangle,楊輝三角1,2

[leetcode]118,119PascalsTriangle,楊輝三角1,2

tco 更新 one lee triangle res 本地 new -1

楊輝三角1
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]
]
構建楊輝三角,從第一行開始構建,比較簡單
public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> res = new ArrayList<>();
        
if (numRows < 1) return res; List<Integer> one = new ArrayList<>(); one.add(1); res.add(one); for (int i = 1; i < numRows; i++) { List<Integer> cur = new ArrayList<>(); cur.add(1); int num = 1;
while (num < i) { cur.add(res.get(i-1).get(num)+res.get(i-1).get(num-1)); num++; } cur.add(1); res.add(cur); } return res; }



楊輝三角2
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?
要求直接輸出第K行
由於有空間限制,只能在本地進行構建楊輝三角,內循環用來更新數據,外循環用來記錄第幾行

public  List<Integer> getRow(int rowIndex) {
        List<Integer> res = new ArrayList<>();
        if(rowIndex<0)
            return res;
        //第一行
        res.add(1);
        for(int i=1;i<=rowIndex;i++)
        {
            //從後邊開始向前更新數據,第一個數不更新
            for(int j=res.size()-2;j>=0;j--)
            {
                //當前的數加上前邊的數就是下一行的當前位置數
                res.set(j+1,res.get(j)+res.get(j+1));
            }
            //循環完後加上最後的1就是更新好了一行
            res.add(1);
        }
        return res;
    }




[leetcode]118,119PascalsTriangle,楊輝三角1,2