Leetcode 78.子集

题目:78.子集

初始思路

休息日,写两题练练。

代码

  1. var subsets = function (nums) {
  2. const res = []
  3. const dfs = (index, list) => {
  4. // 结束条件
  5. if (index === nums.length) {
  6. // 指针越界,加入题解
  7. res.push(list.slice())
  8. return
  9. }
  10. // 选择index所在的数
  11. list.push(nums[index])
  12. // 基于这个选择,继续递归
  13. dfs(index + 1, list)
  14. // 撤销这个选择,往上回溯
  15. list.pop()
  16. // 不选这个index,继续递归
  17. dfs(index + 1, list)
  18. }
  19. dfs(0, [])
  20. return res
  21. };

感想

  1. 回溯问题,没练过啊。
  2. [1,2,3]的输出是:[[1,2,3],[1,2],[1,3],[1],[2,3],[2],[3],[]]
  3. 题解:https://leetcode.cn/problems/subsets/solution/shou-hua-tu-jie-zi-ji-hui-su-fa-xiang-jie-wei-yun-/

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

题目:121.买卖股票的最佳时机

初始思路

恩。。。之前做过贪心的

代码

  1. var maxProfit = function (prices) {
  2. if (prices.length <= 1) return 0
  3. let result = 0, min = prices[0]
  4. for (let i = 0; i < prices.length; i++){
  5. result = Math.max(res, prices[i] - min)
  6. min = Math.min(prices[i], min)
  7. }
  8. return result
  9. };

感想

  1. 这题实际上是要用动态规划做的,但是还没刷到那里。