题解 | #递归,杨辉三角#
杨辉三角的变形
http://www.nowcoder.com/practice/8ef655edf42d4e08b44be4d777edbf43
import java.util.* ; public class Main{ public static void main(String...args) { Scanner sc = new Scanner(System.in) ; while(sc.hasNextLine()) { Integer n = Integer.parseInt(sc.nextLine()) ; int[] ret = tri(n) ; boolean has = false ; for(int i = 0 ; i < ret.length ; i++) { if(ret[i]%2 == 0) { has = true ; System.out.println(i+1) ; break ; } } if(!has) { System.out.println(-1) ; } } } //返回第n行的数组 public static int[] tri(int n) { if(n == 1) { return new int[]{1} ; } if(n == 2) { return new int[]{1,1,1} ; } //上一行 int up[] = tri(n-1) ; int now[] = new int[up.length+2] ; now[0] = now[now.length-1] = 1 ; for(int i = 1 ; i <= now.length/2 ; i ++) { if(i == 1) { now[i] = up[i-1]+up[i] ; continue ; } now[i] = up[i-2] + up[i-1] + up[i] ; } int i = 0 ; int j = now.length-1 ; while(i < j) { now[j] = now[i] ; j -- ; i ++ ; } return now ; } }
一个菜鸟的算法刷题记录 文章被收录于专栏
分享一个菜鸟的成长记录