Which part is wrong with my solution?


  • 0
    L
    public class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> triangle = new ArrayList<List<Integer>>();
    	List<Integer> onerow = new ArrayList<Integer>();
    	if(numRows < 1) return triangle;		
    	for(int i = 1 ; i <= numRows ; i++){
    		for(int j = i - 1 ; j > 1 ; j--){
    			onerow.set(j-1, onerow.get(j-2) + onerow.get(j-1));
    		}
    		onerow.add(1);
    		triangle.add(onerow);
    	}
    	return triangle;    
    }
    

    }

    The output always repeats the last row, it's like [[1, 3, 3, 1], [1, 3, 3, 1], [1, 3, 3, 1], [1, 3, 3, 1]] when numRows = 4. I cannot figure out why everytime I add the same arraylist to the result in the loop.


  • 0
    S

    If you initialize a new List<Integer>onerow each time instead of using the same one it will work..


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.