LeetCode:再帰的に三角形の印刷方法

免責事項:この記事はブロガーオリジナル記事です、続くBY-SAのCC 4.0を著作権契約、複製、元のソースのリンクと、この文を添付してください。
このリンク: https://blog.csdn.net/qq_41885819/article/details/102685822

コードは以下の通りであります:

package com.leetcode.recurse;

import java.util.ArrayList;
import java.util.List;

public class YangHuiTriangle {
	List<List<Integer>> fatherList = new ArrayList<List<Integer>>();
	public static void main(String[] args) {
		List<List<Integer>> list = new YangHuiTriangle().generate(5);
		System.out.println(list);
	}
	/**
	 * 
	 * @param numRows
	 * @return 通过给定的非负数,返回杨辉三角形
	 */
	public List<List<Integer>> generate(int numRows) {
		
		if(numRows==1) {
			List<Integer> childList = new ArrayList<Integer>();
			childList.add(1);			
			fatherList.add(childList);			
		}else if(numRows>1){
			fatherList = generate(numRows-1);
			List<Integer> childList = new ArrayList<Integer>();
			int len = fatherList.size();
			int before=0,now=0;
			for(int index : fatherList.get(len-1)) {				
				now = index;
				childList.add(before+now);
				before = index;
			}
			childList.add(now);
			fatherList.add(childList);			
		}       
        return fatherList;
    }

}

出力の実装:

[1]、[1,1]、[1、2、1]、[1、3、3、1]、[1、4、6、4、1]]

 

おすすめ

転載: blog.csdn.net/qq_41885819/article/details/102685822