黑马程序员技术交流社区
标题:
四种方式打印杨辉三角,步步优化
[打印本页]
作者:
清香白莲
时间:
2015-5-3 10:13
标题:
四种方式打印杨辉三角,步步优化
import java.util.*;
public class HelloJava
{
//使用不规则二维数组
public static void printYanghuiTriangle_1(int n)
{
int[][] a = new int[n][];
for (int i = 0; i < n; ++i)
{
a[i] = new int[i + 1];
a[i][0] = a[i][i] = 1;
for (int j = 1; j < i; ++j)
a[i][j] = a[i - 1][j] + a[i - 1][j - 1];
}
for (int[] x : a)
{
for (int e : x)
System.out.print(e + " ");
System.out.println();
}
}
//使用长度为n的一维数组
public static void printYanghuiTriangle_2(int n)
{
int[] a = new int[n];
for (int i = 0; i < n; ++i)
{
a[i] = 1;
for (int j = i - 1; j > 0; --j)
a[j] += a[j - 1];
for (int j = 0; j <= i; ++j)
System.out.print(a[j] + " ");
System.out.println();;
}
}
//使用长度为(n + 1) / 2的一维数组
public static void printYanghuiTriangle_3(int n)
{
System.out.println(1);
if (n == 1)
return;
System.out.println(1 + " " + 1);
if (n == 2)
return;
int[] a = new int[(n + 1) / 2];
a[0] = 1;
for (int i = 2; i < n; ++i)
{
int lastIndex = i / 2;
if (i % 2 == 0)
a[lastIndex] = a[lastIndex - 1] << 1;
else
a[lastIndex] += a[lastIndex - 1];
for (int j = lastIndex - 1; j > 0; --j)
a[j] += a[j - 1];
for (int j = 0; j <= lastIndex; ++j)
System.out.print(a[j] + " ");
if (i % 2 == 1)
System.out.print(a[lastIndex] + " ");
for (int j = lastIndex - 1; j >= 0; --j)
System.out.print(a[j] + " ");
System.out.println();
}
}
//不使用数组
public static void printYanghuiTriangle_4(int n)
{
for (int i = 0; i < n; ++i)
{
int x = 1;
System.out.print(x + " ");
for (int j = 1; j <= i; ++j)
{
x = x * (i - j + 1) / j;
System.out.print(x + " ");
}
System.out.println();
}
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
printYanghuiTriangle_1(sc.nextInt());
printYanghuiTriangle_2(sc.nextInt());
printYanghuiTriangle_3(sc.nextInt());
printYanghuiTriangle_4(sc.nextInt());
sc.close();
}
}
复制代码
作者:
清香白莲
时间:
2015-5-3 10:16
对于第四种方法,需要二项式定理和组合数的相关知识。
作者:
突然世界晴
时间:
2015-5-3 16:40
看不懂,但是很流弊的样子
作者:
程梦真
时间:
2015-5-3 16:53
。。。。。。。。。。。。。。。。。
作者:
lixunwen
时间:
2015-5-3 17:45
感谢分享 我最开始只用了二维数组来编程。
作者:
liuyang10908126
时间:
2015-10-22 15:16
越往后面代码也越简单!
作者:
Sayman
时间:
2015-10-22 15:58
学习一下
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2