A leetcode problem: Given numRows, generate the first numRows of Pascal's triangle.
The C++ version of this algorithm got accepted by Leetcode. Could anyone tell me why this Java version cannot get accepted?
public class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (numRows == 0) return result;
List<Integer> raw = new ArrayList<Integer>();
raw.add(1);
result.add(raw);
if (numRows == 1) return result;
List<Integer> row = raw;
List<Integer> row2 = raw;
for (int i = 2; i <= numRows; i++) {
for (int j = 0; j < row.size()-1; j++)
row2.add(row.get(j) + row.get(j+1));
row2.add(1);
result.add(row2);
row = row2;
row2 = raw;
}
return result;
}
}
Could anyone tell me why this Java version cannot get accepted?
Because your code runs forever.
You have exactly one List<Integer>
and it keeps growing:
for (int j = 0; j < row.size()-1; j++)
row2.add(row.get(j) + row.get(j+1));
In each iteration you move one element forward and add one element, to the same list, essentially eternally chasing the end that keeps getting away.
(I had a friend at uni who initially also didn't understand how references work in Java and made a similar mistake with Lists. He got like a bazillion buttons in a Swing GUI.)