0

I am trying to create a function that will return an array with the power set of a given string, w/c is the set of all possible subsets including the empty set.

All characters in a subset should be sorted and sets of the same characters are considered duplicates regardless of order and count only once, e.g. 'ab' and 'ba' are the same.

For instance:

allSet("jump")

 * -> ["", "j", "ju", "jm", "jp", "jmu", "jmp", "jpu", "jmpu", "u", "m", "p", "mu", "mp", "pu", "mpu"]
 */

I've been trying to figure out the logic behind and try to use recursion but I just can't:

var allSet = function(str) {
  let result = [];
  let strCopy = str.split('');
  strCopy = strCopy.slice();

  for (var i = 0; i < str.length; i++) {
    result.push(str[i]);
  }

  result = result.concat(allSet(strCopy));

  return result;
};

allSet("jump");

Can anyone help me with this and help me understand the solution logic in layman's term? (example/analogy would be helpful) Sorry a dummy here.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122

1 Answers1

1

You can take this approach using recursion:

var allSet = function(str) {
  let result = [];
  let strCopy = str.split('');
  strCopy = strCopy.slice();
  
  // Base condition
  if(str.length==0){
    return [""];
  }

  // Call function again with str removing the first char
  var _rec = allSet(str.slice(1));
  
  // Add first char on all the elements of _rec
  var _rec2 = _rec.map(el => str.charAt(0) + el);
  
  // Join both the arrays
  return _rec.concat(_rec2);
};

console.log(allSet("jump"));
void
  • 36,090
  • 8
  • 62
  • 107