LeetCode

北城余情 提交于 2020-12-16 19:56:20

Topic

  • Array

Description

https://leetcode.com/problems/pascals-triangle/

Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.

In Pascal's triangle, each number is the sum of the two numbers directly above it.

Example:

Input: 5
Output:
[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

Analysis

方法一:我写的

方法二:别人写的

Submission

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

public class PascalsTriangle {
	public List<List<Integer>> generate1(int numRows) {
		List<List<Integer>> result = new ArrayList<>();
		if (numRows <= 0)
			return result;

		for (int i = 1; i <= numRows; i++) {
			List<Integer> tempList = new ArrayList<>();

			for (int j = 0; j < i; j++) {
				if (j == 0 || j == i - 1) {
					tempList.add(1);
					continue;
				}

				List<Integer> lastList = result.get(i - 2);
				tempList.add(lastList.get(j) + lastList.get(j - 1));
			}

			result.add(tempList);
		}

		return result;
	}

	public List<List<Integer>> generate2(int numRows) {
		List<List<Integer>> allrows = new ArrayList<List<Integer>>();
		ArrayList<Integer> row = new ArrayList<Integer>();
		for (int i = 0; i < numRows; i++) {
			row.add(0, 1);
			for (int j = 1; j < row.size() - 1; j++)
				row.set(j, row.get(j) + row.get(j + 1));
			allrows.add(new ArrayList<Integer>(row));
		}
		return allrows;

	}
}

Test

import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;

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

import org.junit.Test;

public class PascalsTriangleTest {

	@Test
	public void test() {
		PascalsTriangle obj = new PascalsTriangle();

		List<List<Integer>> expected = new ArrayList<List<Integer>>();
		
		expected.add(Arrays.asList(1));
		expected.add(Arrays.asList(1,1));
		expected.add(Arrays.asList(1,2,1));
		expected.add(Arrays.asList(1,3,3,1));
		expected.add(Arrays.asList(1,4,6,4,1));
		
		assertThat(obj.generate1(5), is(expected));
		assertThat(obj.generate2(5), is(expected));
		
		
	}
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!