可以使用递归的方式来实现这个排列组合的函数,下面是一个示例的实现:

function getCombinations(arr) {
  const result = [];
  
  function helper(current, remaining) {
    result.push(current); // 将当前组合加入结果数组
    
    for (let i = 0; i < remaining.length; i++) {
      helper(current.concat(remaining[i]), remaining.slice(i + 1)); // 递归调用helper函数
    }
  }
  
  helper([], arr); // 初始调用helper函数
  
  return result;
}

// 示例调用
const arr = [1, 2, 3];
const combinations = getCombinations(arr);
console.log(combinations);

运行以上代码,输出结果为:`[[1],[2],[3],[1,2],[1,3],[2,3],[1,2,3]]

我需要写一个js方法传入一个数组返回该数组所有元素的排列组合比如传入123返回值是123121323123

原文地址: https://www.cveoy.top/t/topic/iL8p 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录