Accepted Java solution using recursion


  • 0
    S
    public class Solution {
        public List<List<Integer>> generate(int numRows) {
            if(numRows<1) {
                List<List<Integer>> rl = new ArrayList<List<Integer>>();
                return rl;
            }
            if(numRows==1){
                List<Integer> r = new ArrayList<Integer>();
                r.add(1);
                List<List<Integer>> rl = new ArrayList<List<Integer>>();
                rl.add(r);
                return rl;
            }
            if(numRows==2){
                List<Integer> r1 = new ArrayList<Integer>();
                r1.add(1);
                List<Integer> r2 = new ArrayList<Integer>();
                r2.add(1);
                r2.add(1);
                List<List<Integer>> rl = new ArrayList<List<Integer>>();
                rl.add(r1);
                rl.add(r2);
                return rl;
            }
            List<List<Integer>> oldrl = generate(numRows-1);
            List<Integer> oldRow = oldrl.get(oldrl.size()-1);
            List<Integer> newRow = new ArrayList<Integer>();
            newRow.add(1);
            for(int i=0;i<oldRow.size()-1;i++){
                newRow.add(oldRow.get(i)+oldRow.get(i+1));
            }
            newRow.add(1);
            oldrl.add(newRow);
            return oldrl;
            
            
        }
    }

Log in to reply
 

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