LC 121. 买卖股票的最佳时机

股票问题系列通解

LC 122. 买卖股票的最佳时机 II

股票问题系列通解

LC 123. 买卖股票的最佳时机 III

股票问题系列通解

LC 131. 分割回文串

  1. class Solution {
  2. List<List<String>> results = new ArrayList<>();
  3. List<String> result = new ArrayList<>();
  4. String s;
  5. public List<List<String>> partition(String s) {
  6. this.s = s;
  7. backtracking(0);
  8. return results;
  9. }
  10. public void backtracking(int startIndex) {
  11. if (startIndex == s.length()) {
  12. results.add(new ArrayList<>(result));
  13. return;
  14. }
  15. for (int i = startIndex; i < s.length(); i++) {
  16. if (judge(s, startIndex, i)) {
  17. result.add(s.substring(startIndex, i + 1));
  18. } else {
  19. continue;
  20. }
  21. backtracking(i + 1);
  22. result.remove(result.size() - 1);
  23. }
  24. }
  25. public boolean judge(String s, int l, int r) {
  26. boolean empty = s.isEmpty();
  27. if (empty == true) {
  28. return true;
  29. }
  30. while (l <= r) {
  31. if (s.charAt(l) != s.charAt(r)) {
  32. return false;
  33. }
  34. l++;
  35. r--;
  36. }
  37. return true;
  38. }
  39. }

LC 135. 分发糖果

回溯 + 备忘录的话,严重超内存

  1. class Solution {
  2. int[] ratings;
  3. int minSum = Integer.MAX_VALUE;
  4. public int candy(int[] ratings) {
  5. this.ratings = ratings;
  6. backTracking(-1, 0, 0);
  7. return minSum;
  8. }
  9. // num 表示下标为 index 的孩子的糖果数量
  10. // sum 表示下标为 index 及之前的孩子的糖果总数量
  11. public void backTracking(int index, int num, int sum) {
  12. if (index == ratings.length - 1) {
  13. if (sum < minSum) {
  14. minSum = sum;
  15. }
  16. return;
  17. }
  18. for (int i = 1; i <= ratings.length; i++) {
  19. if (index >= 0) {
  20. int temp = ratings[index + 1] - ratings[index];
  21. if (temp > 0 && i <= num) {
  22. i = num + 1;
  23. } else if (temp < 0 && i >= num) {
  24. break;
  25. }
  26. }
  27. backTracking(index + 1, i, sum + i);
  28. }
  29. }
  30. }

LC 188. 买卖股票的最佳时机 IV

股票问题系列通解