[LintCode]杨辉三角

思路描述

给一整数 n, 返回杨辉三角的前 n 行

  1. 0 <= n <= 20
  2. 杨辉三角也被叫做帕斯卡三角形. --(Wikipedia)

样例

给出 n = 4
返回
[
 [1]
 [1,1]
 [1,2,1]
 [1,3,3,1]
]

1.杨辉三角第n行的元素个数为n 

2.每个数字等于它两肩上的数字相加

arr[i][j]=a[i-1][j-1]+a[i-1][j];

3.首尾均为1

①:

import java.util.Scanner;

public class Solution {

	public static void main(String[] args){
		Scanner sc=new Scanner(System.in);
		int n=sc.nextInt();
		int[][]A=new int[n][n];
		for(int i=0;i<n;i++){
			for(int j=0;j<=i;j++){
				if(j==0||j==i){
					A[i][j]=1;
				}
			}
		}
		for(int i=1;i<n;i++){
			for(int j=1;j<i;j++){
				A[i][j]=A[i-1][j-1]+A[i-1][j];
			}
		}
		for(int i=0;i<n;i++){
			for(int j=0;j<=i;j++){
				System.out.print(A[i][j]+" ");
			}
			System.out.println();
		}
	}
}

import java.util.*;
public class Solution {
/**
* @param n: a Integer
* @return: the first n-line Yang Hui's triangle
*/
public List<List<Integer>> calcYangHuisTriangle(int n) {
    List<List<Integer>> yanghui = new ArrayList(n);
    List<Integer> a;
    for(int i=1;i<=n;i++) {
        a = new ArrayList(i);
        for(int j=1;j<=i;j++) {
            if(j==1||j==i)
            a.add(new Integer(1));
            else
            a.add(yanghui.get(i-2).get(j-2)+yanghui.get(i-2).get(j-1));
            
        }
        yanghui.add(a);
        
    }
    return yanghui;
    }
}
扫描二维码关注公众号,回复: 2843187 查看本文章

猜你喜欢

转载自blog.csdn.net/yizhidamanman/article/details/81410118