Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LeetCode题解:78. 子集,递归+for循环+回溯,JavaScript,详细注释 #206

Open
chencl1986 opened this issue Oct 30, 2020 · 0 comments

Comments

@chencl1986
Copy link
Owner

原题链接:https://leetcode-cn.com/problems/subsets/

解题思路:

  1. 使用DFS生成所有可能的排列情况。
  2. 每层递归从current开始遍历nums
  3. 将遍历到的值存入subset,并进入下一层递归,表示当前值存在与子集中的情况。
  4. 进入下一层递归后,将当前值从subset中弹出,继续遍历数组,表示当前值不存在与子集中的情况。
function dfs(nums, subset, result, current) {
  // 每次递归的参数subset,都是在上一层生成的子集,直接将其存入结果
  result.push(subset.slice());

  // 从current开始遍历,current之前的元素都已被遍历过
  // 并且已经被按照是否存储两种情况存入子集
  // i < nums.length充当了递归终止条件
  for (let i = current; i < nums.length; i++) {
    // 下一层递归的current
    const newCurrent = i + 1;
    // 将当前值存入子集,并且进入下一层递归
    // 下一层递归处理的是当前值存在与子集中的情况
    subset.push(nums[i]);
    // 进入下一层递归
    dfs(nums, subset, result, newCurrent);
    // 将当前值弹出,继续当前的for循环遍历
    // 当前层的继续遍历,处理了当前值不存在与子集中的情况
    subset.pop();
  }
}
/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var subsets = function (nums) {
  let result = []; // 存储结果
  let subset = []; // 存储子集
  // 使用DFS+回溯生成所有子集
  dfs(nums, subset, result, 0);
  return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant