Leetcode - Pascal's Triangle II

Leetcode - Pascal's Triangle II_第1张图片
Paste_Image.png

My code:

import java.util.ArrayList;
import java.util.List;

public class Solution {
    public List getRow(int rowIndex) {
        List result = new ArrayList();
        int row = rowIndex + 1;
        if (row <= 0)
            return result;
        else if (row == 1) {
            result.add(1);
            return result;
        }
        else if (row == 2) {
            result.add(1);
            result.add(1);
            return result;
        }
        int[] arrayK = new int[row];
        arrayK[0] = 1;
        arrayK[1] = 1;
        for (int i = 3; i <= row; i++) {
            int[] temp = new int[row];
            for (int j = 0; j < i; j++) {
                if (j == 0)
                    temp[j] = 1;
                else if (j == i - 1)
                    temp[j] = 1;
                else
                    temp[j] = arrayK[j - 1] + arrayK[j];
            }
            arrayK = temp;
        }
        
        for(int i = 0; i < row; i++)
            result.add(arrayK[i]);
        return result;
    }
    
    public static void main(String[] args) {
        Solution test = new Solution();
        System.out.println(test.getRow(5));
    }
}

My test result:

Leetcode - Pascal's Triangle II_第2张图片
Paste_Image.png

这次作业也比较简单吧。

**
总结:Today is my birthday. Hope everything will fine in the next year.
**

Anyway, Good luck, Richardo!

My code:

public class Solution {
    public List getRow(int rowIndex) {
        ArrayList ret = new ArrayList();
        if (rowIndex < 0)
            return ret;
        int[] level = new int[rowIndex + 1];
        level[0] = 1;
        for (int i = 1; i < rowIndex + 1; i++) {
            for (int j = i - 2; j >= 0; j--) {
                level[j + 1] += level[j];
            }
            level[i] = 1;
        }
        for (int i = 0; i <= rowIndex; i++)
            ret.add(level[i]);
        return ret;
    }
}

用一个数组从右往左模拟。还是很快的。代码也比以前的简洁。

Anyway, Good luck, Richardo!

你可能感兴趣的:(Leetcode - Pascal's Triangle II)