题解 | no#杨辉三角的变形#

杨辉三角的变形

https://www.nowcoder.com/practice/8ef655edf42d4e08b44be4d777edbf43

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
   
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNextInt()) {
            int num = in.nextInt();
            if(num == 1 || num == 2){
                System.out.println(-1);
                continue;
            }
            else if(num % 4 == 1 || num % 4 == 3){
                System.out.println(2);
                continue;
            }
            else if(num % 4 == 0){
                System.out.println(3);
                continue;
            }
            else if(num % 4 == 2){
                System.out.println(4);
                continue;
            }
        }
    }

}

 Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[][] result = new int[n][];
        //生成对应多少行的二维数组金字塔  当n = 10000 在牛客网编译不过 太耗时
        for (int i = 0; i < n; i++) {
            result[i] = new int[2*i+1];

            for (int j = 0; j < 2*i+1; j++) {
                if (j==0 ||j==2*i){
                    result[i][j] = 1;
                }else if (j==1 || j==2*i-1){
                    if (i==1){
                        result[i][j]=1;
                    }else {
                        result[i][j]=result[i-1][0] +result[i-1][1];
                    }
                }else {
                    if (j<=i){
                        result[i][j]=result[i-1][j-2]+result[i-1][j-1]+result[i-1][j];
                    }else {
                        result[i][j]=result[i][2*i-j];
                    }
                }
            }
        }
        for (int i:result[n-1]) {
            System.out.print(i);
        }
        System.out.println("/n");
        //找到金字塔对应行中最先出现偶数的位置
        for (int i = 0; i < 2*n-1; i++) {
            int i1 = result[n - 1][i];
            if (i1%2==0){
                System.out.println(i+1);
                return;
            }
        }
        System.out.println(-1);

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务