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

Answer:

  1. Use DFS to generate all possible permutations.
  2. Each layer recurses fromcurrentTo traverse thenums.
  3. Store the traversed valuesubsetAnd enter the next level of recursion, indicating that the current value exists in a subset.
  4. After entering the next level of recursion, the current value is changed fromsubsetTo continue traversing the number group, indicating that the current value does not exist in the subset.
function dfs(nums, subset, result, current) {
  // Each recursive parameter subset is the subset generated in the previous layer, which is directly saved into the result
  result.push(subset.slice());

  // Start traversal from current, all elements before current have been traversed
  // And has been stored in the subset according to whether or not to store
  // I < nums.length acts as a recursive termination condition
  for (let i = current; i < nums.length; i++) {
    // The next level of recursion is current
    const newCurrent = i + 1;
    // Put the current value into the subset and proceed to the next level of recursion
    // The next level of recursion deals with cases where the current value exists in a subset
    subset.push(nums[i]);
    // Go to the next level of recursion
    dfs(nums, subset, result, newCurrent);
    // Pop the current value and continue the current for loop
    // Continue traversal of the current layer, handling the case that the current value does not exist in the subsetsubset.pop(); }}/ * * *@param {number[]} nums
 * @return {number[][]}* /
var subsets = function (nums) {
  let result = []; // Store the result
  let subset = []; // Store subsets
  Use DFS+ backtrace to generate all subsets
  dfs(nums, subset, result, 0);
  return result;
};
Copy the code