Algorithm 使用uniq元素将数组拆分为s个子集

Algorithm 使用uniq元素将数组拆分为s个子集,algorithm,combinations,Algorithm,Combinations,给定一个数组[1,2,3,4,5]和代表拆分的数字s如何生成以下序列(希望我涵盖了s=3的所有组合) 已排序的数组和每个子集s必须至少包含1个元素 s = 2 {1} {2, 3, 4, 5} {1, 2} {3, 4, 5} {1, 2, 3}, {4, 5} {1, 2, 3, 4}, { 5 } {1, 2, 3, 4, 5} s = 3 {1}, {2}, {3, 4, 5} {1}, {2, 3}, {4, 5} {1}, {2, 3, 4}, {5} {1, 2}, {3, 4},

给定一个数组[1,2,3,4,5]和代表
拆分的数字s
如何生成以下序列(希望我涵盖了s=3的所有组合)

已排序的数组和每个子集
s
必须至少包含1个元素

s = 2
{1} {2, 3, 4, 5}
{1, 2} {3, 4, 5}
{1, 2, 3}, {4, 5}
{1, 2, 3, 4}, { 5 }
{1, 2, 3, 4, 5}

s = 3
{1}, {2}, {3, 4, 5}
{1}, {2, 3}, {4, 5}
{1}, {2, 3, 4}, {5}
{1, 2}, {3, 4}, {5}
{1, 2, 3}, {4}, {5}
{1, 2}, {3}, {4, 5}
{1, 2, 3}, {4}, {5}

s=2
时,我可以解决此问题,但当
s>2
时,我不知道该怎么办我看到您描述为的问题“N个代码中的m”或代码

N是单词的长度(在你的例子中是5-1=4) m是重量或您要进行的拆分次数(-s)

单词:1-+-2-+-3-+-4-+-5 分割位置:1 2 3 4

然后,您可以说您的拆分是一个布尔数组(当您要进行拆分时,拆分位置数组中的位为true或1)

因此,您有一个代码,其中有四(N-1)个可能的位,其中两个位必须为真。 即N=4,s=2

[0011],
[0101],
[1001], etc.
正如维基百科所说,没有分析方法来定义任意组合的可能性数量。但对于较小的数字,您只需使用简单程序的蛮力方法即可。用python编写的,它不是最具python风格的,但更容易阅读

代码:

def check(m,N):
    candidates = range(0, 2**(N-1))
    valid_candidates = []
    for candidate in candidates:
        binary_representation = [int(x) for x in list(('{:0%sb}' % (N-1)).format(candidate))]
        if sum(binary_representation) == m:
            #found candidate
            print(binary_representation)
            valid_candidates.append(binary_representation)
    return valid_candidates


if __name__ == "__main__":
    N = 5
    s = 2
    print("Number of valid combinations with N=%s and s=%s is: %s " %(N, s, len(check(s, N))))
[0, 0, 1, 1]
[0, 1, 0, 1]
[0, 1, 1, 0]
[1, 0, 0, 1]
[1, 0, 1, 0]
[1, 1, 0, 0]
Number of valid combinations with N=5 and s=2 is: 6
输出:

def check(m,N):
    candidates = range(0, 2**(N-1))
    valid_candidates = []
    for candidate in candidates:
        binary_representation = [int(x) for x in list(('{:0%sb}' % (N-1)).format(candidate))]
        if sum(binary_representation) == m:
            #found candidate
            print(binary_representation)
            valid_candidates.append(binary_representation)
    return valid_candidates


if __name__ == "__main__":
    N = 5
    s = 2
    print("Number of valid combinations with N=%s and s=%s is: %s " %(N, s, len(check(s, N))))
[0, 0, 1, 1]
[0, 1, 0, 1]
[0, 1, 1, 0]
[1, 0, 0, 1]
[1, 0, 1, 0]
[1, 1, 0, 0]
Number of valid combinations with N=5 and s=2 is: 6

实现这一点的一种方法是使用递归。类似于以下内容(JavaScript代码):

函数f(arr,k){
如果(k==1)
返回[[arr]];
var结果=[];
对于(var i=1;i result.push([head].concat(x));
}
返回结果;
}
log(JSON.stringify(f([1,2,3,4,5],3))