Leetcode 78.子集
题目:78.子集
初始思路
代码
var subsets = function (nums) {const res = []const dfs = (index, list) => {// 结束条件if (index === nums.length) {// 指针越界,加入题解res.push(list.slice())return}// 选择index所在的数list.push(nums[index])// 基于这个选择,继续递归dfs(index + 1, list)// 撤销这个选择,往上回溯list.pop()// 不选这个index,继续递归dfs(index + 1, list)}dfs(0, [])return res};
感想
- 回溯问题,没练过啊。
- [1,2,3]的输出是:[[1,2,3],[1,2],[1,3],[1],[2,3],[2],[3],[]]
- 题解:https://leetcode.cn/problems/subsets/solution/shou-hua-tu-jie-zi-ji-hui-su-fa-xiang-jie-wei-yun-/
Leetcode 121.买卖股票的最佳时机
初始思路
代码
var maxProfit = function (prices) {if (prices.length <= 1) return 0let result = 0, min = prices[0]for (let i = 0; i < prices.length; i++){result = Math.max(res, prices[i] - min)min = Math.min(prices[i], min)}return result};
感想
- 这题实际上是要用动态规划做的,但是还没刷到那里。
