Original link: leetcode-cn.com/problems/su…

Answer:

  1. Exhaust all sets with two cycles of violence.
  2. The first loop is going to befor (let i = 0; i < 1 << nums.length; i++) {}, that is, the number of all subsets is exhausted, but the judgment of whether to store values is not made.
  3. Second cyclefor (let j = 0; j < nums.length; j++) {}, that is, traverse each index before passingi & (1 << j)Determines whether the current index needs to store a value.
/ * * *@param {number[]} nums
 * @return {number[][]}* /
var subsets = function (nums) {
  let result = []; // Store the result

  // The first loop
  For example, if nums is [1,2,3], 1 << nums.length generates a binary number 1000
  // This loop iterates through all possible children
  for (let i = 0; i < 1 << nums.length; i++) {
    let subset = []; // Store the current possible children

    // Loop the second time
    // Use this loop to iterate over the binary number for each index
    for (let j = 0; j < nums.length; j++) {
      // 1 << j generates the binary numbers 1, 10, 100, corresponding to three indexes respectively
      // Each I operates with 1 << j. That is to complete the current win or lose whether to save the value of judgment
      // Each index can be stored or not stored
      if (i & (1 << j)) {
        // Store the values that need to be stored in the current collectionsubset.push(nums[j]); }}// Store the current collection to the result
    result.push(subset);
  }

  return result;
};
Copy the code