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

问题

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3690 访问。

给定一个非负索引 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]


示例

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3690 访问。

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种算法实现,以下是这个案例的输出结果:

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3690 访问。

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方法可以根据杨辉三角的对称性优化,只需计算一半即可,其实现方法留给各位看官。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值