[英]Find all combinations of a given set of numbers
說我有一組數字'0','1','2',......,'9'。 我想找到所有數字,其中只包含我的集合中每個數字中的一個。
問題是:在我開始我的程序之前,我不知道我的設置將包括多少個數字和數字。 (例如,該集合可以包含數字'1','3'和'14'。)
我搜索了互聯網,偶然發現了“動態編程”這個術語,這個術語顯然是用來解決像我這樣的問題,但我不明白這些例子。
有人能給我一個如何解決這個問題的提示(可能是動態編程)嗎?
編輯:當集合包括像'14'這樣的數字時,集合的不同數量當然必須通過某種方式分開,例如當集合包括數字'1','3'和'14'時,組合可以是1-3-14或3-14-1(=由' - '字符分隔的個別數字)。
對我來說,看起來你正在尋找一組給定元素的所有排列。
如果您使用C ++,則有一個標准函數next_permutation()
可以完全滿足您的要求。 您從排序的數組開始,然后重復調用next_permutation
。
示例如下: http : //www.cplusplus.com/reference/algorithm/next_permutation/
要在不事先知道必須有多少位數的情況下檢查所有組合,我曾寫過這段代碼:
#include <stdio.h>
#include <stdlib.h>
#define ARRSIZE(arr) (sizeof(arr)/sizeof(*(arr)))
int main()
{
const char values[]= {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
char * buffer=NULL;
int * stack=NULL;
int combinationLength=-1;
int valuesNumber=-1;
int curPos=0;
fprintf(stderr, "%s", "Length of a combination: ");
if(scanf("%d", &combinationLength)!=1 || combinationLength<1)
{
fputs("Invalid value.\n",stderr);
return 1;
}
fprintf(stderr, "%s (%lu max): ", "Possible digit values",(long unsigned)ARRSIZE(values));
if(scanf("%d", &valuesNumber)!=1 || valuesNumber<1 || (size_t)valuesNumber>ARRSIZE(values))
{
fputs("Invalid value.\n", stderr);
return 1;
}
buffer=(char *)malloc(combinationLength);
stack=(int *)malloc(combinationLength*sizeof(*stack));
if(buffer==NULL || stack==NULL)
{
fputs("Cannot allocate memory.\n", stderr);
free(buffer);
free(stack);
return 2;
}
/* Combinations generator */
for(;;)
{
/* If we reached the last digit symbol... */
if(stack[curPos]==valuesNumber)
{
/* ...get back to the previous position, if we finished exit */
if(--curPos==-1)
break;
/* Repeat this check */
continue;
}
buffer[curPos]=values[stack[curPos]];
/* If we are in the most inner fake-cycle write the combination */
if(curPos==combinationLength-1)
puts(buffer);
stack[curPos]++;
/* If we aren't on the last position, start working on the next one */
if(curPos<combinationLength-1)
{
curPos++;
stack[curPos]=0;
}
}
/* Cleanup */
free(buffer);
free(stack);
return 0;
}
它只是在一個周期內完成所有操作,以避免遞歸和函數調用開銷,仍然使用堆棧數組“偽造”所需的嵌套for循環。
它表現相當不錯,在我4歲的Athlon64 3800+上需要2'4“的用戶時間(=>實際計算時間)來生成36 ^ 6 = 2176782336組合,因此它每秒計算大約1750萬個組合。
matteo@teoubuntu:~/cpp$ gcc -Wall -Wextra -ansi -pedantic -O3 combinations.c -o combinations.x
matteo@teoubuntu:~/cpp$ time ./combinations.x > /media/Dati/combinations.txt
Length of a combination: 6
Possible digit values (36 max): 36
real 13m6.685s
user 2m3.900s
sys 0m53.930s
matteo@teoubuntu:~/cpp$ head /media/Dati/combinations.txt
000000
000001
000002
000003
000004
000005
000006
000007
000008
000009
matteo@teoubuntu:~/cpp$ tail /media/Dati/combinations.txt
zzzzzq
zzzzzr
zzzzzs
zzzzzt
zzzzzu
zzzzzv
zzzzzw
zzzzzx
zzzzzy
zzzzzz
matteo@teoubuntu:~/cpp$ ls -lh /media/Dati/combinations.txt
-rwxrwxrwx 1 root root 15G 2010-01-02 14:16 /media/Dati/combinations.txt
matteo@teoubuntu:~/cpp$
“實際”時間相當高,因為我同時也在PC上做了其他事情。
有多少個數字,哪些數字不是兩個問題。 如果你知道哪些數字,你知道多少。
這些數字的名稱不是很有趣。 1-3-14或0-1-2或Foo-Bar-Baz - 它始終是同一個問題,與0-1-2和數組的排列相同的問題,在哪里查找結果。
idx nums words
0 1 foo
1 3 bar
2 14 baz
最方便的解決方案是,編寫一個通用的Iterable。 然后,您可以使用簡化的for循環來訪問每個排列。
import java.util.*;
class PermutationIterator <T> implements Iterator <List <T>> {
private int current = 0;
private final long last;
private final List <T> lilio;
public PermutationIterator (final List <T> llo) {
lilio = llo;
long product = 1;
for (long p = 1; p <= llo.size (); ++p)
product *= p;
last = product;
}
public boolean hasNext () {
return current != last;
}
public List <T> next () {
++current;
return get (current - 1, lilio);
}
public void remove () {
++current;
}
private List <T> get (final int code, final List <T> li) {
int len = li.size ();
int pos = code % len;
if (len > 1) {
List <T> rest = get (code / len, li.subList (1, li.size ()));
List <T> a = rest.subList (0, pos);
List <T> res = new ArrayList <T> ();
res.addAll (a);
res.add (li.get (0));
res.addAll (rest.subList (pos, rest.size ()));
return res;
}
return li;
}
}
class PermutationIterable <T> implements Iterable <List <T>> {
private List <T> lilio;
public PermutationIterable (List <T> llo) {
lilio = llo;
}
public Iterator <List <T>> iterator () {
return new PermutationIterator <T> (lilio);
}
}
class PermutationIteratorTest {
public static void main (String[] args) {
List <Integer> la = Arrays.asList (new Integer [] {1, 3, 14});
PermutationIterable <Integer> pi = new PermutationIterable <Integer> (la);
for (List <Integer> lc: pi)
show (lc);
}
public static void show (List <Integer> lo) {
System.out.print ("(");
for (Object o: lo)
System.out.print (o + ", ");
System.out.println (")");
}
}
您正在尋找一組給定值的所有排列。
有關Java中“做”排列的文章如下: http : //www.bearcave.com/random_hacks/permute.html
你想跳過前幾節,直到你進入標題排列算法 (當然)。
這是我可以發現有用的排列的C#3.0實現
public static class PermutationExpressions
{
public static IEnumerable<IEnumerable<T>> Permutations<T>(this IEnumerable<T> list)
{
return list.Permutations((uint)list.Count());
}
public static IEnumerable<IEnumerable<T>> Permutations<T>(this IList<T> list)
{
return list.Permutations((uint)list.Count);
}
private static IEnumerable<IEnumerable<T>> Permutations<T>(this IEnumerable<T> list, uint n)
{
if (n < 2) yield return list;
else
{
var ie = list.GetEnumerator();
for (var i = 0; i < n; i++)
{
ie.MoveNext();
var item = ie.Current;
var i1 = i;
var sub_list = list.Where((excluded, j) => j != i1).ToList();
var sub_permutations = sub_list.Permutations(n - 1);
foreach (var sub_permutation in sub_permutations)
{
yield return
Enumerable.Repeat(item, 1)
.Concat(sub_permutation);
}
}
}
}
}
[TestFixture]
public class TestPermutations
{
[Test]
public void Permutation_Returns_Permutations()
{
var permutations = PermutationExpressions.Permutations(new[] { "a", "b", "c" }.AsEnumerable());
foreach (var permutation in permutations)
{
Console.WriteLine(string.Join("", permutation.ToArray()));
}
Assert.AreEqual("abc_acb_bac_bca_cab_cba", permutations.Select(perm => perm.joinToString("")).joinToString("_"));
}
}
與動態編程無關; 除非你想在褲子外面穿內褲並在胸前塗上一個符號。
簡單的方法是維護一個0-9的整數數組,然后逐個遍歷數字並遞增數組[num]。 一旦處理完所有數字,結果就是查看數組中的任何元素是非零還是一個。 (這表示重復的數字。)當然,取一個數字然后使用模數和除數逐位迭代是微不足道的。
所以,假設您有數字1,2和3。
如果您期望六個數字123,132,213,231,312和321是正確的答案,那么您正在尋找的是一些代碼來生成集合的所有排列,這將比幾乎任何其他東西更快對於有趣的問題的問題。 你看O(n!)是最好的情況。
您應該編寫一個循環遍歷列表的遞歸函數,並且每次使用更新的列表調用自身。 這意味着它需要使用N-1個元素創建列表的副本以傳遞給下一個迭代。 對於結果,您需要在每次迭代中追加當前選定的數字。
string Permutations(List numbers, string prefix)
{
foreach (current_number in numbers)
{
new_prefix = prefix+"-"+number;
new_list=make_copy_except(numbers, current_number)
if (new_list.Length==0)
print new_prefix
else
Permutations(new_list, new_prefix)
}
}
import Data.List (inits, tails)
place :: a -> [a] -> [[a]]
place element list = zipWith (\front back -> front ++ element:back)
(inits list)
(tails list)
perm :: [a] -> [[a]]
perm = foldr (\element rest -> concat (map (place element) rest)) [[]]
test = perm [1, 3, 14]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.