[英]how to generate the following sequence?
我想生成以下序列:
set S = {1,2,3}
op = {{1,2},{1,3},{2,3}}
set S = {1,2,3,4}
op = {{1,2,3},{1,2,4},{1,3,4},{2,3,4}}
set S = {1,2,3,4,5}
op = {{1,2,3,4},{1,2,3,5},{1,2,4,5},{1,3,4,5},{2,3,4,5}}
通常,給定一組n個數字,我必須找到(n-1)個數字的所有可能子集,並限制它們按字母順序(數字順序)。
是否有解決特定問題的算法或方法? 我知道我們可以使用遞歸來生成較小的子集。
這樣的子集只有n
。 每一個都從原始集中刪除了n
原始編號之一。 因此,對集合進行排序,並為每個數字創建一個集合,該集合是刪除了該數字的原始集合。
可能的警告是,如果原始集中存在重復的數字,則子集的數目將與原始集中唯一的數目一樣多,因此在這種情況下可能少於n
。
某些語言內置了此功能。 例如,Python的itertools.combinations()
方法 。 在您的情況下:
>>> import itertools
>>> l = [1,2,3,4]
>>> combinations = itertools.combinations(l, len(l) - 1) #for the list of numbers l, for sublists with a length 1 less than l's length
>>> for comb in combinations:
... print comb
...
(1, 2, 3)
(1, 2, 4)
(1, 3, 4)
(2, 3, 4)
>>>
但是,如果您想自己實現,上面的鏈接可能仍然有用,因為它顯示了等效的代碼。 您可以使用此代碼以任何語言進行自己的實現。
這應該足夠簡單。 令arr具有排序的集合,n為元素的數量:
int arr[100];
int n;
printf("{");
for (int i = n - 1; i >= 0; i--){
printf("{");
for (int j = 0; j < n; j++) {
if (i == j) {
continue;
}
printf("%d, ", arr[j]);
}
printf("}, ");
}
printf("}\n");
上面打印了一些其他逗號,您可以自己過濾掉它們。
想一想
從1..N生成/打印集
print "{"
for i=1 to N
if (i > 1) print ","
print i
end
print "}"
如何創建一個從N到1中選擇n的循環
for j=N to 1
...
end
使用最后一個循環作為上述循環的包裝器-並在上述循環測試中,如果當前選定的數字j等於i,並且在這種情況下不進行打印。
出於樂趣,Perl的實現並沒有被優化:-)
$N = 5;
sub rec {
my($j,$i,@a) = @_;
if ($j > 0) {
while (++$i <= $N) { push(@a,$i) if ($i != $j); }
print('{' . join(',', @a) . "}\n");
&rec($j-1);
}
}
&rec($N);
還是這個(也許)更傳統
for ($i=$N ; $i>0 ; $i--) {
@a = ();
for (1..$N) { push(@a,$_) if ($i != $_); }
print('{' . join(',', @a) . "}\n");
}
在Haskell你可以做這個 :
import Data.List
combinations 0 _ = [ [] ]
combinations n xs = [ y:ys | y:xs' <- tails xs
, ys <- combinations (n-1) xs']
subsets set = combinations (length set - 1) (sort set)
Haskell,簡要地:
_ => anyting
[] => empty list
a = 1; as = [2,3] => a:as = [1,2,3]
[a:b | a <- [1], b <- [[2],[3]]] => [[1,2],[1,3]]
tails [1,2,3] => [[1,2,3],[2,3],[3],[]]
例如,“組合2 [1,2,3]”:
tails xs = [[1,2,3],[2,3],[3],[]]
[1,2,3] => y = 1; ys = [[2],[3]] => [1,2],[1,3]
[2,3] => y = 2; ys = [[3]] => [2,3]
[3] => y = 3; ys = NULL => []
Result [[1,2],[1,3],[2,3]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.