C#LeetCode刷题之#119-杨辉三角 II(Pascal's Triangle II)

版权声明:Iori 的技术分享,所有内容均为本人原创,引用请注明出处,谢谢合作! https://blog.csdn.net/qq_31116753/article/details/82086257

问题

给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 行。

在杨辉三角中,每个数是它左上方和右上方的数的和。

输入: 3

输出: [1,3,3,1]

你可以优化你的算法到 O(k) 空间复杂度吗? 


Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle.

Note that the row index starts from 0.


In Pascal's triangle, each number is the sum of the two numbers directly above it.

Could you optimize your algorithm to use only O(k) extra space? 

Input: 3

Output: [1,3,3,1]


示例

public class Program {

    public static void Main(string[] args) {
        var res = GetRow(4);
        var res2 = GetRow2(5);

        ShowArray(res);
        ShowArray(res2);

        Console.ReadKey();
    }

    private static void ShowArray(IList<int> array) {
        foreach(var num in array) {
            Console.Write($"{num} ");
        }
        Console.WriteLine();
    }

    private static IList<int> GetRow(int rowIndex) {
        int[][] res = new int[rowIndex + 1][];
        for(int i = 0; i < res.Length; i++) {
            res[i] = new int[rowIndex + 1];
        }
        res[0][0] = 1;
        for(int i = 1; i < rowIndex + 1; i++) {
            res[i][0] = 1;
            for(int j = 1; j < i + 1; j++) {
                res[i][j] = res[i - 1][j - 1] + res[i - 1][j];
            }
        }
        return res[rowIndex];
    }

    private static IList<int> GetRow2(int rowIndex) {
        int[] res = new int[rowIndex + 1];
        res[0] = 1;
        for(int i = 1; i < rowIndex + 1; i++) {
            for(int j = rowIndex; j >= 1; j--) {
                res[j] = res[j - 1] + res[j];
            }
        }
        return res;
    }

}

以上给出2种算法实现,以下是这个案例的输出结果:

1 4 6 4 1
1 5 10 10 5 1

分析:

显而易见,GetRow在最坏的情况下的时间复杂度为: O(n^{2}) ,空间复杂度也为:O(n^{2}) ;

GetRow2在最坏的情况下的时间复杂度为: O(n^{2}) ,由于使用一维数组空间复杂度为: O(n) 。

GetRow2方法可以根据杨辉三角的对称性优化,只需计算一半即可,其实现方法留给各位看官。

猜你喜欢

转载自blog.csdn.net/qq_31116753/article/details/82086257