杨辉三角 -(列数不等二维数组)
做法1
目的 :打印一个杨辉三角 ?ω?
型如:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
...
为了更好的发现规律,稍微给这个原始的杨辉三角做点 处理 : ●ω●
a b c d e f
a 1 0
b 1 1 0
c 1 2 1 0
d 1 3 3 1 0
e 1 4 6 4 1 0
...
当你把每一行的首尾都 定死为1和0 ,那么会得到一点 规律 :<( ̄︶ ̄)>
变化的部分永远都是中间的那个三角区域

也就是说,大概可以得出这样的一个等式 (在第1列和第一行定死数字且每行最后一个数字定死为0的情况下)
假设当前的位置为 (x,y) ,值为 n ,n=(x-1,y-1)+(x-1,y) ;
(x-1,y-1)和(x-1,y) 都表示一个 二维坐标 。
核心都明白了,接下来直接上代码了. ~( ̄▽ ̄)~*
import java.util.Scanner; public class YanHui { public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in); int height = 6; int width = 2; int[][] arr = new int[height][];
arr[0] = new int[width]; arr[0][0] = 1; for (int i = 1;i <height;i++ ) { width++; arr[i] = new int[width]; arr[i][0] = 1; for (int j=1; j<width-1;j++ ) { arr[i][j] = arr[i-1][j-1]+arr[i-1][j]; } } System.out.println("高度为"+height+"的杨辉三角:"); for (int i=0;i<arr.length ;i++ ) { for (int j=0;j<arr[i].length-1 ;j++ ) { System.out.print(arr[i][j]+"\t"); } System.out.println(""); } } }
|
最终会实现如下的效果: ̄▽ ̄

其实做法有很多种,比如:
做法2
1.第一行1个元素,第n行n个元素
2.每行首末都是1
3.第三行开始,除去第一个元素与最后一个元素外,
arr[i][j]=arr[i-1][j]+arr[i-1][j-1]
这种做法比先前的思路简便些,感觉代码实现也略微简单些。
public class YanHui03 { public static void main(String[] args) { int height = 6; int width = 0; int[][] yanghui = new int[height][]; for (int i = 0;i < yanghui.length ;i++ ) { yanghui[i] = new int[i+1]; width = i+1; for (int j = 0;j < width ;j++ ) { if (j==0||j==width-1) { yanghui[i][j] = 1; } else { yanghui[i][j] = yanghui[i-1][j]+yanghui[i-1][j-1]; } } } System.out.println("打印高度为"+height+"的杨辉三角所有的元素:"); for (int i=0;i<yanghui.length ;i++ ) { for (int j=0;j<yanghui[i].length ;j++ ) { System.out.print(yanghui[i][j]+" "); } System.out.println(""); } } }
|
效果图和之前那个差不多啦ヽ(ˋ▽ˊ)ノ
