生成一个号码的所有不同的分区

编程入门 行业动态 更新时间:2024-10-23 01:43:08
本文介绍了生成一个号码的所有不同的分区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我试图写一个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); } }

更多推荐

生成一个号码的所有不同的分区

本文发布于:2023-11-29 00:37:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1644595.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:分区   号码

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!