我正在尝试生成字符串的所有大写排列。
例如:
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))
问题: 它将进入无限递归。即使我有一个破坏条件。如果有人可以纠正我出错的地方,我将不胜感激。
蓝山帝景
吃鸡游戏
阿晨1998
相关分类