【问题标题】:How to get all the possible set of a word - JS [duplicate]如何获得所有可能的单词集-JS [重复]
【发布时间】:2018-02-19 14:37:55
【问题描述】:

我正在尝试创建一个函数,该函数将返回一个具有给定字符串的幂集的数组,w/c 是所有可能子集的集合,包括空集。

应该对子集中的所有字符进行排序,并且相同字符的集合被认为是重复的,无论顺序如何,并且只计算一次,例如'ab' 和 'ba' 是一样的。

例如:

allSet("jump")

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

我一直在试图找出背后的逻辑并尝试使用递归,但我就是做不到:

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");

任何人都可以帮助我并帮助我理解外行术语的解决方案逻辑吗? (示例/类比会有所帮助)抱歉,这里是个傻瓜。

【问题讨论】:

标签: javascript recursion


【解决方案1】:

您可以使用递归来采用这种方法:

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"));

【讨论】:

    猜你喜欢
    • 2013-04-24
    • 1970-01-01
    • 2012-11-25
    • 2015-02-16
    • 1970-01-01
    • 2021-08-21
    • 2012-02-07
    • 2013-12-01
    • 2011-05-16
    相关资源
    最近更新 更多