相关疑难解决方法(0)

JavaScript中的排列?

我正在尝试编写一个执行以下操作的函数:

  • 将整数数组作为参数(例如[1,2,3,4])
  • 创建一个包含[1,2,3,4]所有可能排列的数组,每个排列的长度为4

下面的函数(我在网上找到)通过将一个字符串作为参数,然后返回该字符串的所有排列来完成此操作

我无法弄清楚如何修改它以使其与整数数组一起使用(我认为这与某些方法在字符串上的工作方式不同于它们在整数上的工作方式有关,但我不确定. ..)

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中找到了如何做到这一点

javascript permutation

127
推荐指数
14
解决办法
11万
查看次数

在c ++中查找字符串的所有排列

以下是打印给定字符串的所有排列的代码.代码编译但不打印任何内容.

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)

需要修复什么?

c++ string

3
推荐指数
2
解决办法
2万
查看次数

标签 统计

c++ ×1

javascript ×1

permutation ×1

string ×1