zoukankan      html  css  js  c++  java
  • LeetCode——Pascal's Triangle II

    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?

    原题链接:https://oj.leetcode.com/problems/pascals-triangle-ii/

    题目:给定一个索引k,返回帕斯卡三角形的第k行。

    思路 : 此题能够用上一题中的方法来解。直接就是通项公式,与k行之前的行没有关系。

    也能够一次分配结果所需大小的list。每次计算一行,并将结果置于合适的位置,下一行採用上一行的结果进行计算。

    	public static List<Integer> getRow(int rowIndex) {
    		if (rowIndex < 0)
    			return null;
    
    		List<Integer> result = new ArrayList<Integer>(rowIndex + 1);
    		result.add(1);
    
    		for (int i = 1; i <= rowIndex; i++) {
    			int temp1 = 1;
    			for (int j = 1; j < i; j++) {
    				int temp2 = result.get(j); 
    				result.set(j, temp1 + temp2);
    				temp1 = temp2;
    			}
    			result.add(1); 
    		}
    
    		return result;
    	}

    reference : http://www.darrensunny.me/leetcode-pascals-triangle-ii/


  • 相关阅读:
    Detect Capital
    Maximum Depth of Binary Tree
    Max Consecutive Ones
    Single Number
    Nim Game
    Longest Uncommon Subsequence I
    Average of Levels in Binary Tree
    Next Greater Element I
    Island Perimeter
    Fizz Buzz
  • 原文地址:https://www.cnblogs.com/lytwajue/p/7007634.html
Copyright © 2011-2022 走看看