集/数组中的每个(特定大小的)组合,没有重复的项目 [英] Every (specific sized) combination from set/array with no duplicate items

查看:42
本文介绍了集/数组中的每个(特定大小的)组合,没有重复的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有设置= [1、2、3、4、5、6、7]

Let's say I have set = [1, 2, 3, 4, 5, 6, 7]

我想要以下回报[1、2、3、4、5][4,3,2,1,6][7,5,1,3,2] .......

I'd like the following in return [1, 2, 3, 4, 5] [4, 3, 2, 1, 6] [7, 5, 1, 3, 2]..........

本质上,正如标题所述,我希望从数组中生成特定大小的组合,但是每个组合都不能包含任何重复项(因此,如果您有这个想法,那么就不会有aaab,aaac).

Essentially, as the title states I'm looking to generate specific sized combinations from an array but each combination can't have any duplicate items (so no aaab, aaac if you get the idea).

我在这里也找到了另一个问题,但是在组合中却存在重复.我试图调整并编写递归函数无济于事:/

I've found another question here as well, but it had dupes within the combinations. I've tried tweaking and writing the recursive function to no avail :/

推荐答案

好的-所有可能的子集都没有重复,并且假设顺序无关紧要,即 [1、2、3、4、5] [5,4,3,2,1] 相同.简约示例:

Alright - all possible subsets without duplicates and assuming that the order does not matter, i.e. [1, 2, 3, 4, 5] is the same as [5, 4, 3, 2, 1]. Minimalistic example:

<?php
$arr = array(1, 2, 3, 4, 5, 6, 7);

function getSubsets($set, $items) {
  $result = array();
  getSubsets2($set, $items, 0, array(), $result);
  return $result;
}

function getSubsets2($set, $items, $index, $current, &$result) {
  if (sizeof($current) === $items) {
    $result[] = $current;
    return;
  }
  if ($index < sizeof($set)) {
    getSubsets2($set, $items, $index + 1, $current, $result);
    $current[] = $set[$index];
    getSubsets2($set, $items, $index + 1, $current, $result);
  }
}

$subsets = getSubsets($arr, 5);

echo(sizeof($subsets)); // 21
?>

不要背负别人的桂冠:这是基于用Java编写的另一个堆栈溢出答案的100%.

Not to carry off someone else's laurels: This is 100% based on another Stack Overflow answer written in java.

这篇关于集/数组中的每个(特定大小的)组合,没有重复的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆