首页 > 解决方案 > 字符串排列时的递归问题

问题描述

我正在尝试生成字符串的所有大写排列。

例如:

capitalPermutations(word) - 给定一串字母,返回该单词的所有可能的小写和大写字母组合。

示例:'abc'

输出:['abc''Abc''aBc''ABc''abC''AbC''aBC''ABC']

以迭代和递归的方式实现这一点。

这是我的尝试:

function capitalPermutations(word) {
  const res = new Set();
  
  // Push the actual word first.
  res.add(word);
  
  helper(word, res, '');
  
  return res;
  
  function helper(word, res, str='') {
    
    if(str.length === word.length) return;
    
    const len = word.length;
    res.add(word);
    
    // Capitalization
    for(let i=0; i< word.length; i++) {
      const substr = word.substring(0, i+1); // a, ab, abc
      str += substr; // str === "ABC" | len = 3
      const upper = str.toUpperCase(); // A, AB, ABC
      const remaining = `${upper}${word.substring(i, len)}`; // Abc , ABc, 
      helper(remaining, res, str);
    }
  }

}
var testWord1 = "abc"
console.log(capitalPermutations(testWord1))

问题: 它将进入无限递归。即使我有一个破碎的条件。如果有人能纠正我出错的地方,我将不胜感激。

标签: javascriptrecursion

解决方案


这是一个带有flatMap的:

function f(str){
  return str ? f(str.slice(1)).flatMap(sfx =>
    [str[0].toLowerCase() + sfx, str[0].toUpperCase() + sfx]) : [""]
}

console.log(JSON.stringify(f("abc")))


推荐阅读