Skip to content

LeetCode题解:78. 子集,迭代+位运算,JavaScript,详细注释 #205

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

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

Comments

@chencl1986
Copy link
Owner

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

解题思路:

  1. 用两遍循环暴力穷尽所有集合。
  2. 第一遍循环是for (let i = 0; i < 1 << nums.length; i++) {},即穷尽了所有子集数量,但不做是否存值的判断。
  3. 第二遍循环for (let j = 0; j < nums.length; j++) {},即遍历每个索引,在通过i & (1 << j)判断当前索引是否需要存值。
/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var subsets = function (nums) {
  let result = []; // 存储结果

  // 第一遍循环
  // 以nums为[1 ,2 ,3]为例,1 << nums.length生成的为二进制数1000
  // 该循环遍历了所有可能的子级
  for (let i = 0; i < 1 << nums.length; i++) {
    let subset = []; // 存储当前可能的子级

    // 第二遍循环
    // 利用该循环,遍历出每个索引对应的二进制数
    for (let j = 0; j < nums.length; j++) {
      // 1 << j生成的是二进制数1、10、100,分别对应3个索引
      // 每个i都与1 << j进行与操作。即完成了当前输赢是否要存入值的判断
      // 也就是每个索引都有存或不存值两种该状态
      if (i & (1 << j)) {
        // 将需要存储的值,存入当前集合中
        subset.push(nums[j]);
      }
    }

    // 将当前集合存入结果
    result.push(subset);
  }

  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