本文介绍了生成一个号码的所有不同的分区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图写一个C code生成所有可能的分区(到2个或更多份)的不同的的给定数目的元素。一个给定的分区的所有数字的总和应等于给定数。例如,对于输入每组6 ,系统具有2个或更多个元件以不同元件的所有可能的分区是:

I am trying to write a C code to generate all possible partitions (into 2 or more parts) with distinct elements of a given number. The sum of all the numbers of a given partition should be equal to the given number. For example, for input n = 6, all possible partitions having 2 or more elements with distinct elements are:

  • 1,5
  • 在1,2,3
  • 2,4

我觉得递归的方法应该可行,但我不能把不同元素的添加约束的照顾。伪code或样品code在C / C ++ / Java的将是极大的AP preciated。

I think a recursive approach should work, but I am unable to take care of the added constraint of distinct elements. A pseudo code or a sample code in C/C++/Java would be greatly appreciated.

谢谢!

编辑::如果它使事情变得更容易,我可以忽略其至少有2个单元分区的限制。这将允许号码自身被添加到列表中(例如,6本身将是微不足道的,但有效的分区)。

If it makes things easier, I can ignore the restriction of the partitions having atleast 2 elements. This will allow the number itself to be added to the list (eg, 6 itself will be a trivial but valid partition).

推荐答案

我勾勒这个解决方案(也可以美化和优化),这不应该产生重复的:

I sketched this solution (it can be beautified and optimized) that shouldn't generate duplicates:

void partitions(int target, int curr, int* array, int idx)
{
    if (curr + array[idx] == target)
    {
        for (int i=0; i <= idx; i++)
            cout << array[i] << " ";
        cout << endl;
        return;
    }
    else if (curr + array[idx] > target)
    {
        return;
    }
    else
    {
        for(int i = array[idx]+1; i < target; i++)
        {
            array[idx+1] = i;
            partitions(target, curr + array[idx], array, idx+1);
        }
    }
}

int main(){
    int array[100];
    int N = 6;
    for(int i = 1; i < N; i++)
    {
        array[0] = i;
        partitions(N, 0, array, 0);
    }
}

这篇关于生成一个号码的所有不同的分区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 08:57