必须通过找规律得出结果,采用构造杨辉三角的方式会计算超时
参考大佬的代码
import java.util.Scanner;
/**
* 【杨辉三角的变形】
*
*
*/
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int input = sc.nextInt();
if (input == 1 || input == 2) {
System.out.println(-1);
}
else if (input % 4 == 3 || input % 4 == 1) {
System.out.println(2);
}
else if (input % 4 == 0) {
System.out.println(3);
} else {
System.out.println(4);
}
}
}
下面代码计算超时:
import java.util.Scanner;
/**
* 【杨辉三角的变形】
*
*
*/
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int high = sc.nextInt();
int length = high * 2 - 1;
int[][] ints = new int[high][length];
ints[0][high - 1] = 1;
for (int i = 1; i < high; i++) {
for (int j = 1; j < length - 1; j++) {
ints[i][j] = ints[i - 1][j - 1] + ints[i - 1][j] + ints[i - 1][j + 1];
}
}
boolean flag = false;
int count = 1;
for (int i = 1; i < length; i++) {
if ((ints[high - 1][i] != 0) && (ints[high - 1][i] % 2 == 0)) {
flag = true;
break;
} else {
count++;
}
}
System.out.println(flag? count + 1 : -1);
}
}