题目描述
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,以下每行的每个数,是恰好是它上面的数,左上角数到右上角的数,3个数之和(如果不存在某个数,认为该数就是0)。
求第n行第一个偶数出现的位置。如果没有偶数,则输出-1。例如输入3,则输出2,输入4则输出3。
输入n(n <= 1000000000)
import java.util.*;
public class Main {
**//法一:list方法**
//参考leetcode的杨辉三角方法改的
//利用arraylist的下标从0开始,只保留最后一行的数据可以节省空间
public static int yanghuitrangle(int rows) {
if(rows < 3) {
return -1;
}
List<Integer> last = new ArrayList<Integer>();
last.add(0);
last.add(1);
last.add(1);
last.add(1);
last.add(0);
for(int i=2; i<rows; ++i) {
List<Integer> temp = new ArrayList<Integer>();
temp.add(0);
temp.add(1);
for(int j=2; j<=i*2; ++j) {//注意!!!这里i*2
//System.out.println(last.get(j) + " " + last.get(j-1) + " " + last.get(j-2));
temp.add(last.get(j) + last.get(j-1) + last.get(j-2));//这里get:j之前写的i
}
temp.add(1);
temp.add(0);
last = temp;
}
int res = -1;
for(int i=1; i<last.size(); ++i) {
if(0 == last.get(i)%2) {
res = i;
break;
}
}
return res;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int rows = 0;
while(scan.hasNextInt()) {
rows = scan.nextInt();
//System.out.println(yanghuitrangle(rows));
System.out.println(yanghui2(rows));
**//法三:抖机灵不推荐**-因为题意一旦改为输出位置和值,改方法就抓瞎了
//if(rows<=2)
// System.out.println(-1);
//else if(rows%2==1)
// System.out.println(2);
//else if(rows%4==0)
// System.out.println(3);
//else
// System.out.println(4);
}
scan.close();
}
**//法二:数组**
//思路:1.找规律,发现,如果用数组表示的话,第1行的1并不是在最左边,而是在第n个元素位置(n代表行号)
// 2.除第一个外,按照公式:a[i][j]=a[i-1][j-1]+a[i-1][j]+a[i-1][j+1];
public static int yanghui2(int num) {
int cow = num;
int line = num*2+1;//因为下面行数要加上面行的三个数,所以每行的两边都要为0才能不越界
int[][] ints = new int[cow][line];
ints[0][num]=1;
for (int i=1;i<cow;i++){
for (int j=1;j<line-1;j++){//注意:起始和结束为止,0==j和line==j都是0(每行的两边)
ints[i][j]=ints[i-1][j-1]+ints[i-1][j]+ints[i-1][j+1];
}
}
int res = -1;
for (int i=1;i<2*num;i++){
if (ints[cow-1][i]%2==0){
//System.out.println(ints[num-1][i]);
res = i;
break;
}
}
return res;
}
}