Leetcode notes: Pascal & amp; #39; s Triangle II

Source: Internet
Author: User

Leetcode Note: Pascal & #39; s Triangle II

I. Description

Given an indexk, ReturnkTh row of the Pascal's triangle.

For example, givenk = 3,
Return[1,3,3,1].

Note:
Cocould you optimize your algorithm to use onlyO(k)Extra space?

Ii. Question Analysis

For the definition of Pascal triangle, see: http://baike.baidu.com/link? Url = qk _-urYQnO4v6v3P4BuMtCa0tMNUqJUk4lmbkb1aqbqikBU-ndiMlTF20fq2QUjTTFTeTohZ72KFxgBnz4sJha

This question requires that only the element value of row k be output, and the spatial complexity isO(k)Therefore, only one fixed-length array is used to store the element values of each row. For each new row, the original row can be scanned from the back to the front, there are three main situations:

The last element is directly equal to 1. For intermediate elements whose subscript is I, there are: result[i] = result[i-1] + result[i]; The first element is directly equal to 1;

In this way, you only needO(k).

Iii. Sample Code

class Solution {public:    vector
  
    getRow(int rowIndex)     {        vector
   
     result(rowIndex + 1);        result[0] = 1;        if (rowIndex < 1) return result;        for(int i = 1; i <= rowIndex; ++i)            for(int j = i; j >= 0; --j)                if (j == i || j == 0)                    result[j] = 1;                else                    result[j] = result[j-1] + result[j];        return result;                        }};
   
  

Iv. Summary

If notO(k)The space complexity of the question is lower, but there is no skill at all.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.