LoginSignup
0
0

More than 1 year has passed since last update.

118 解答

Posted at

参考:
ArrayList, LinkedList の違い
Nick White

解答

public List<List<Integer>> generate(int numRows) {
		List<List<Integer>> ans = new ArrayList<>();
		
		if(numRows == 0) return ans;
		
		List<Integer> first_row = new ArrayList<>();
		first_row.add(1);
		ans.add(first_row);//最初の要素は絶対1だから
		
		for(int i = 1; i < numRows; i++) {
			List<Integer> prev_row = ans.get(i-1);
			List<Integer> current_row = new ArrayList<>();
			
			current_row.add(1);//rowごとに考えた場合、最初は1だから
			for(int j = 1; j < i; j++) {
				current_row.add(prev_row.get(j-1) + prev_row.get(j));
				
			}
			current_row.add(1);//最後の要素も常に1のため
			ans.add(current_row);
		}
		return ans;
		
	}

マイナスになる 不正解

愚直に計算すると

public List<List<Integer>> generate(int numRows) {
		List<List<Integer>> ans = new LinkedList<List<Integer>>();
		
		for (int row = 0; row < numRows; row++) {
			
			List<Integer> temp = new LinkedList<>();
			
			for (int col = 0; col < row + 1; col++) {
				System.out.println("row: "+ row+" col: "+ col);
				System.out.println(factorial(row) + "/" +factorial(row-col)*factorial(col));
				temp.add(col, Math.toIntExact(factorial(row)/(factorial(row-col)*factorial(col))));
				
			}
			ans.add(row,temp);
		}
		return ans;
	}

	public long factorial(int n) {
	    return LongStream.rangeClosed(1, n)
	        .reduce(1, (long x, long y) -> x * y);
	}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0