迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

JavaScript 中的排列

作者:迹忆客 最近更新:2024/03/16 浏览次数:

在 JavaScript 中,有 slicereducefiltersubstring 和更多方法来缓解置换给定字符串或数组的所有可能试验的基本问题。

在这里,我们将展示如何从给定的输入中提取数组和字符串的组合。主要重点是将每个文字从数组或字符串中分开,并一一交换其他文字。

在以下部分中,我们将使用必要的代码示例详细讨论该过程。


给定数组的排列

我们将初始化一个函数 permute,其中包含另一个函数 backtrack。将递归调用此函数 backtrack 以执行正确的组合集。

代码片段:

var permute = function(nums) {
  var result = [];
  var backtrack = (i, nums) => {
    if (i === nums.length) {
      result.push(nums.slice());
      return;
    }
    for (let j = i; j < nums.length; j++) {
      [nums[i], nums[j]] = [nums[j], nums[i]];
      backtrack(i + 1, nums);
      [nums[i], nums[j]] = [nums[j], nums[i]];
    }
  } backtrack(0, nums);
  console.log(result);
  return result;
};
permute([1, 2, 3]);

输出:

这里的主要动作定义了交换部分,我们在其中将每个文字彼此交换一次试验(例如 [1,2,3])并提出可能的组合。

从试验 [1,2,3],我们将得到 [1,2,3] & [1,3,2]。这部分将被执行,直到每个文字都得到检查。

在切换到下一个试验之前,我们通过再次交换返回到基本试验(1,2,3)(因为最后一个组合是 [1,3,2])。这就是回溯的操作方式。

形成一棵树以查看可能的试验,并且树的长度等于数组的长度。最初,我们执行一个 DFS 来解决这个问题,然后递归回溯过程来解决这个问题。


给定字符串的排列

在字符串的情况下,我们将首先拆分字符串,然后我们将使用 reduce 方法通过递归调用 permutationString 函数来逐个连接可能的试验。

代码片段:

var permutationString = str => {
  if (str.length <= 2)
    return str.length === 2 ? [str[0] + str[1], str[1] + str[0]] : [str];
  return str.split('').reduce(
      (accumulator, letter, i) => accumulator.concat(
          permutationString(str.slice(0, i) + str.slice(i + 1))
              .map(val => letter + val)),
      []);
};
console.log(permutationString('abcd'));

输出:

根据累加器功能,我们正在保留每个组合。

我们使用 slice 方法来锁定某个字母表,并根据之前初始化的基本情况添加其余的字母表。最后,输出结果是所有预期模式的组合形式。

阶乘公式推导出方法排列,因此该问题的解决方案通常会遇到较大情况下的运行时错误。但是可以通过这种方式指导具有适当可视化问题的基本推理。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

用 jQuery 检查复选框是否被选中

发布时间:2024/03/24 浏览次数:102 分类:JavaScript

在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便