1.杨辉三角
思路:没什么好解释的,我奶奶都能写出来
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;
}
}
- 杨辉三角 II
思路:。。。
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);
}
}
- 买卖股票的最佳时机
思路:前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;
}
}