Quantcast
Channel: CSDN博客推荐文章
Viewing all articles
Browse latest Browse all 35570

[LeetCode],Pascal's Triangle, 解题报告

$
0
0

题目

Given numRows, generate the first numRows of Pascal's triangle.
For example, given numRows = 5,
Return




思路

典型的杨辉三角题目,说一下构造杨辉三角的思路:

每个数字等于上一行的左右两个数字之和。可用此性质写出整个杨辉三角。即第n+1行的第i个数等于第n行的第i-1个数和第i个数之和,这也是组合数的性质之一

AC代码

import java.util.*;

public class PascalTriangle {
    public static ArrayList<ArrayList<Integer>> generate(int numRows) {
        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
        if (numRows < 1) {
            return result;
        }
        ArrayList<Integer> start = new ArrayList<Integer>();
        start.add(1);
        result.add(start);
        
        for (int i = 1; i < numRows; i ++) {
            ArrayList<Integer> pre = result.get(i - 1);
            ArrayList<Integer> cur = new ArrayList<Integer>();
            cur.add(1);
            
            for (int j = 1; j < i; j ++) {
                int tmp = pre.get(j - 1) + pre.get(j);
                cur.add(tmp);
            }
            
            cur.add(1);
            
            result.add(cur);
        }
        
        return result;
    }
    
    
    public static void main(String args[]) {
        int n;
        ArrayList<ArrayList<Integer>> list;
        Scanner cin = new Scanner(System.in);
        
        while (cin.hasNext()) {
            n = cin.nextInt();
            list = generate(n);
            
            for (int i = 0; i < list.size(); i ++) {
                for (int j = 0; j < list.get(i).size(); j ++) {
                    System.out.printf("%d ", list.get(i).get(j));
                }
                System.out.println();
            }
        }
        
        cin.close();
    }
}


后记

本来想再写一道LeetCode上题目再睡觉,但是突然LeetCode OJ访问速度超慢,我是用GAE翻墙的,按理说不应该出现这种情况啊,诡异!!
作者:zinss26914 发表于2013-12-4 0:41:13 原文链接
阅读:236 评论:0 查看评论

Viewing all articles
Browse latest Browse all 35570

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>