2021-07-12算法题

155 阅读1分钟

1.杨辉三角

image.png 思路:没什么好解释的,我奶奶都能写出来

class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> l = new ArrayList<>();
        for (int i = 0; i < numRows; i++) {
            l.add(new ArrayList<>(i));
            for (int j = 0; j <= i; j++) {
                if (j == 0 || j == i) {
                    l.get(i).add(1);
                } else {
                    int val = l.get(i - 1).get(j) + l.get(i - 1).get(j - 1);
                    l.get(i).add(val);
                }
            }
        }
        return l;
    }
}
  1. 杨辉三角 II

image.png 思路:。。。

class Solution {
    public List<Integer> getRow(int rowIndex) {
        List<List<Integer>> l = new ArrayList<>();
        for (int i = 0; i <= rowIndex; i++) {
            l.add(new ArrayList<>(i));
            for (int j = 0; j <= i; j++) {
                if (j == 0 || j == i) {
                    l.get(i).add(1);
                } else {
                    int val = l.get(i - 1).get(j) + l.get(i - 1).get(j - 1);
                    l.get(i).add(val);
                }
            }
        }
        return l.get(rowIndex);
    }
}
  1. 买卖股票的最佳时机

image.png 思路:前i天的最大收益 = max{前i-1天的最大收益,第i天的价格-前i-1天中的最小价格}

class Solution {
    public int maxProfit(int[] prices) {
        if (prices.length == 1) {
            return 0;
        }
        int profit = 0;
        int min = prices[0];
        for (int i = 1; i < prices.length; i++) {
            profit = Math.max(profit, prices[i] - min);
            if (prices[i] < min) {
                min = prices[i];
            }
        }
        return profit;
    }
}