假设我有 N 个元素,我想创建一个包含所有可能的元素分组的列表,其中一次可以有多个 N 元素组。
例如,假设我们有 4 个元素:a、b、c、d。让 [ ] 表示括号内的元素在一个分组中。我正在寻找一种算法(如果可能的话在 Matlab 中),它可以创建一个列表,列出它们可以像这样组合在一起的所有方式:
- a b c d
- [a b] c d
- a [b c] d
- a b [c d]
- [a d] b c
- [a c] b d
- a c [b d]
- [a b] [c d]
- [b c] [a d]
- [a c] [b d]
- [a b c] d
- 一个[b c d]
- b [c d a]
- c [d a b]
- [a b c d]
最佳答案
这个解决方案产生了所有的可能性:
%Generate potential solutions
p=dec2base(0:base2dec('123',4), 4);
%convert to numeric
p=[zeros(size(p,1),1) p-'0'];
for col=2:4
%sort out. in column col a new group index is used, but not all previous indices are used.
valid=max(p(:,1:col-1),[],2)+1>=p(:,col);
p=p(valid,:);
end
输出是一个标记字符的矩阵。例如,1233
在您的符号中是 ab[cd]
。
关于algorithm - 如何从 N 个元素创建所有可能分组的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21515267/