Pascal's Triangle Leetcode Java and C++

Given numRows, generate the first numRows of Pascal's triangle.

For example, given numRows = 5,
Return

[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

 

 

太久没刷题觉得自己啥也不会了。。。但其实不要有畏难情绪是最重要的,做起来就发现还蛮简单的。。。
public class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> result = new ArrayList<>();
        if (numRows <= 0) {
            return result;
        }
        for (int i = 0; i < numRows; i++) {
            List<Integer> array = new ArrayList<>();
            array.add(1);
            if (i > 0) {
                List<Integer> pre = result.get(i - 1);
                int size = pre.size();
                for (int j = 0; j < size; j++) {
                    if (j == size - 1) {
                        array.add(pre.get(j));
                    } else {
                        array.add(pre.get(j) + pre.get(j + 1));
                    }
                }
            }
            result.add(array);
        }
        return result;
    }
}

看了top solution后的改进版本,减少了条件判断:

public class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> result = new ArrayList<>();
        if (numRows <= 0) {
            return result;
        }
        for (int i = 0; i < numRows; i++) {
            List<Integer> array = new ArrayList<>();
            for (int j = 0; j < i + 1; j++) {
                if (j == 0 || j == i) {
                    array.add(1);
                } else {
                    List<Integer> pre = result.get(i - 1);
                    array.add(pre.get(j - 1) + pre.get(j));
                }
            }
            result.add(array);
        }
        return result;
    }
}

 

但看了另一个top solution还是觉得可能自己就是写不好代码了。。。= =?

但也许我写的比较快一点吧?并不好判断。。。

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

 附上c++的解法,和第一种解法的改进版是一样的:

class Solution {
public:
    vector<vector<int>> generate(int numRows) {
        vector<vector<int>> r(numRows);
        
        for (int i = 0; i < numRows; i++) {
            r[i].resize(i + 1);
            r[i][0] = 1, r[i][i] = 1;
            
            for (int j = 1; j < i; j++) {
                r[i][j] = r[i - 1][j - 1] + r[i - 1][j];
            }
        }
        return r;
    }
};

 这么一看c++还真的挺简洁的。

posted @ 2017-06-05 05:21  璨璨要好好学习  阅读(152)  评论(0编辑  收藏  举报