My accepted solution in JAVA


  • 0
    A

    Here is my solution

    For example , If the given rowIndex is 3;

    Firstly , I add 1 to the res - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 0th floor

    Secondly , Starts form i=1(means floor 1) , I build the floor i according to the records of res(res contains previous floor's record). Then I remove all records belongs to floor i-1

    Finally , I get floor rowIndex, and return it.

    public class Solution {
        public List<Integer> getRow(int rowIndex) {
            List<Integer> res=new ArrayList<Integer>();
            res.add(1);
            for(int i=1;i<=rowIndex;i++)
            {
                for(int j=0;j<=i;j++)
                {
                    if(j==0 || j==i) res.add(1);
                    else
                    {
                        int l=res.get(j-1);
                        int r=res.get(j);
                        res.add(l+r);
                    }
                }
                for(int j=0;j<=i-1;j++)
                {
                    res.remove(0);
                }
            }
            return res;
        }
    }

  • 0
    P

    I have similar approach with you. And personally thought this way is easier to understand than other methods even though the time complexity doesn't look good.

    Also I noticed that when rowIndex=35, the number already overflowed for Integers. So I don't think there's any practical reason to improve time complexity here.

    There's one small thing I suggested to improve in your code is : you could overwrite the value for (i-1)th row when you calculate the new line, by such you don't need to remove old elements later.

    public List<Integer> getRow(int rowIndex) {
    	List<Integer> row = new ArrayList<Integer>();
    	
    	row.add(1);	
    	for(int r=1; r<=rowIndex; r++) {
    		int left = row.get(0);
    		for(int i=1; i<r; i++) {
    			int right = row.get(i);
    			row.set(i, left+right);
    			left = right;
    		}
    		row.add(1);
    	}
    	
    	return row;
    }

  • 0
    A

    Sure,this way is really easy to understand.And I haven't think about overflow before, thanks for you comment!


  • 0
    A

    And overwrite is better than I did : )


Log in to reply
 

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