杨辉三角是一个很有特点的三角形,它的左边和右边都是1,而且它的某一行的值等于上一行的y+y-1的值。如图:
所以我们可以用递归得出规律,即当我们的y == 0
或者是x == y
的时候就作为递归的退出条件,否则一直递归调用函数,即fun(x-1,y-1)+fun(x-1,y)
。接下来我们来实现一下。
import java.util.Scanner;
/**
* 杨辉三角
*/
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("请输入行数:");
int s = input.nextInt();
System.out.println("输出的杨辉三角形为:");
for (int i = 0; i < s; i++) {
for (int j = 0; j <= i; j++) {
int m = fun(i, j);
System.out.print(m + " ");
}
System.out.println();
}
}
public static int fun(int x, int y) {
// 当递归到两边的时候返回1
if (y == 0 || x == y) {
return 1;
} else {
return fun(x - 1, y - 1) + fun(x - 1, y);
}
}
}
结果:
BUT
上面这个会超时,所以我们用一个二维数组来实现,这样就不会超时了,
import java.util.Scanner;
/**
* 杨辉三角
*/
public class Main {
static int[][] a = new int[35][35];
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int s = input.nextInt();
for (int i = 1; i <= 34; i++) {
for (int j = 1; j <= i; j++) {
if (j == 1 || i == j) {
a[i][j] = 1;
} else {
a[i][j] = a[i - 1][j - 1] + a[i - 1][j];
}
}
}
for (int i = 1; i <= s; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(a[i][j]+" ");
}
System.out.println();
}
}
}
力扣原题:https://leetcode-cn.com/problems/pascals-triangle/
题解:
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
for(int i=0;i<numRows;i++){
List<Integer> ret = new ArrayList<>();
for(int j=0;j<=i;j++){
if(j==0 || j==i){
ret.add(1);
}else{
ret.add(res.get(i-1).get(j-1)+res.get(i-1).get(j));
}
}
res.add(ret);
}
return res;
}
}