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?

    这题是Pascal's Triangle的升级版,当然思路大致是一样的,leetcode有很多这种升级版的题目,都可以用原来的版本改良得到。这题不要求列出从1—n所有行了,只要求拿出第k行。当然要得到第k行也要从第一行开始推进,只是这里不再需要保存k-1以前的结果,因为k的结果只跟k-1有关,所以只需要O(k)的额外空间。 这里要注意一点的是k是从0开始的,而上一题是从1开始的=_=

    void getRowIter(int index, int n, vector<int> &aux) {
        if (index > n) return;
        vector<int> t;
        
        t.push_back(1);
        for (int k = 0; k < index-1; k++) {
            t.push_back(aux[k]+aux[k+1]);
        }
        t.push_back(1);
        aux = t;
        getRowIter(index+1, n, aux);
    }
    
    
    vector<int> getRow(int rowIndex) {
        vector<int> aux;
        if (rowIndex < 0) return aux;
        aux = {1};
        if (rowIndex == 0) return aux;
        getRowIter(1,rowIndex, aux);
        return aux;
    }
  • 相关阅读:
    Best Time to Buy and Sell Stock
    Remove Nth Node From End of List
    Unique Paths
    Swap Nodes in Pairs
    Convert Sorted Array to Binary Search Tree
    Populating Next Right Pointers in Each Node
    Maximum Subarray
    Climbing Stairs
    Unique Binary Search Trees
    Remove Duplicates from Sorted Array
  • 原文地址:https://www.cnblogs.com/agentgamer/p/4086008.html
Copyright © 2011-2022 走看看