华为OJ平台——杨辉三角的变形

时间:2021-10-07 22:38:46
 import java.util.Scanner;

 /**
* 杨辉三角的变形
*第一行为1,后面每一行的一个数是其左上角到右上角的数的和,没有的记为0
* 1
* 1 1 1
* 1 2 3 2 1
* 1 3 6 7 6 3 1
* 1 4 10 16 19 16 10 4 1
* 1 5。。。
*求第x行的第一个偶数是第几个
*
*/
public class YangHui { public static void main(String[] args) {
Scanner cin = new Scanner(System.in) ;
int line = cin.nextInt() ;
cin.close(); System.out.println(run(line)) ; } /**
* 计算返回值
* @param x
* @return
*/
public static int run(int x){
if(x == 1 || x == 2){
return -1 ;
}
//每一行的第一个数为1,第二个数为n-1;第三个数为 n*(n-1)/2
if(x%2 == 1){
return 2 ;
}else if(x*(x-1)%4 == 0){
return 3 ;
}
//若前三个均不是偶数,则从第四个数开始计算,由于是对称的的,所以判断到第x行的第x个数就可以了
for(int i = 4 ; i <= x ; i++){
int res = cal(x,i) ;
if(res%2 == 0){
return i ;
}
}
return -1 ;
} /**
* 传入n,i表示第n行的第i个,返回其值,递归的方法求解
* @param n
* @param i
* @return
*/
public static int cal(int n, int i){
if(i > n){
return cal(n,2*n-i) ;
}
if(n == 2 && i > 0){
return 1 ;
}
if(i == 1){
return 1 ;
}
if(i <= 0){
return 0 ;
}
int res ;
res = cal(n-1,i) + cal(n-1,i-1) + cal(n-1,i-2) ;
return res ;
} }