My accepted java solution, any improvements?


  • 0
    J

    I use recursive solution. But when numRows =0, 1, 2, it is really very special. So I separated it. recursive can only occur when numRows =3.

    public static List<List<Integer>> generate(int numRows) {
    	List<List<Integer>> result = new ArrayList<List<Integer>>();
    
    	if(numRows == 0){
    		return result;
    	}    	  	
    	
    	if(numRows ==1){
    		List<Integer> level1 = new ArrayList<Integer>();
    		level1.add(1);
    		result.add(level1);
    		return result;
    	}
    	
    	if(numRows ==2){
    		List<Integer> level1 = new ArrayList<Integer>();
    		level1.add(1);
    		result.add(level1);
    
    		List<Integer> level2 = new ArrayList<Integer>();
    		level2.add(1);
    		level2.add(1);
    		result.add(level2);
    		return result;
    	}
    	
    	result = generate(numRows - 1);
    	List<Integer> prelevel = result.get(numRows-2);
    	List<Integer> nextlevel = new ArrayList<Integer>();
    	nextlevel.add(1);
    	for( int i=1; i< numRows -1; i++){
    		nextlevel.add(prelevel.get(i-1) + prelevel.get(i));
    	}
    	nextlevel.add(1);
    	
    	result.add(nextlevel);
    	return result;
    }

  • 0
    P

    yes, check my code.


Log in to reply
 

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