我正在尝试编写一个执行以下操作的函数:
下面的函数(我在网上找到)通过将一个字符串作为参数,然后返回该字符串的所有排列来完成此操作
我无法弄清楚如何修改它以使其与整数数组一起使用(我认为这与某些方法在字符串上的工作方式不同于它们在整数上的工作方式有关,但我不确定. ..)
var permArr = [], usedChars = [];
function permute(input) {
var i, ch, chars = input.split("");
for (i = 0; i < chars.length; i++) {
ch = chars.splice(i, 1);
usedChars.push(ch);
if (chars.length == 0)
permArr[permArr.length] = usedChars.join("");
permute(chars.join(""));
chars.splice(i, 0, ch);
usedChars.pop();
}
return permArr
};
Run Code Online (Sandbox Code Playgroud)
注意:我希望使函数返回整数数组,而不是字符串数组.
我真的需要使用JavaScript的解决方案.我已经在python中找到了如何做到这一点
以下是打印给定字符串的所有排列的代码.代码编译但不打印任何内容.
using namespace std;
void RecPermute(string, string);
int main() {
RecPermute("", "abc");
return 0;
}
void RecPermute(string soFar, string rest) {
if (rest == " ") {
cout << soFar << endl;
} else {
for(int i=0; i<rest.length(); i++) {
string next = soFar + rest[i];
string remaining = rest.substr(0, i) + rest.substr(i+1);
RecPermute(next, remaining);
}
}
}
Run Code Online (Sandbox Code Playgroud)
需要修复什么?