[英]combinations algorithm
我想制作簡單的排序算法。
如果輸入“abcde”,我想要下面的輸出。 你能告訴我算法嗎?
arr[0] = "a"
arr[1] = "ab"
arr[2] = "ac"
arr[3] = "ad"
arr[4] = "ae"
arr[5] = "abc"
arr[6] = "abd"
arr[7] = "abe"
...
arr[n] = "abcde"
arr[n+1] = "b"
arr[n+2] = "bc"
arr[n+3] = "bd"
arr[n+4] = "be"
arr[n+5] = "bcd"
arr[n+5] = "bce"
arr[n+5] = "bde"
...
arr[n+m] = "bcde"
...
...
您正在尋找一種從陣列“生成電源組”的算法。 您可以嘗試使用Google或其他搜索引擎來查找最符合您需求的算法。
在C ++中給出以下例程:
template <typename Iterator>
bool next_combination(const Iterator first, Iterator k, const Iterator last)
{
/* Credits: Mark Nelson http://marknelson.us */
if ((first == last) || (first == k) || (last == k))
return false;
Iterator i1 = first;
Iterator i2 = last;
++i1;
if (last == i1)
return false;
i1 = last;
--i1;
i1 = k;
--i2;
while (first != i1)
{
if (*--i1 < *i2)
{
Iterator j = k;
while (!(*i1 < *j)) ++j;
std::iter_swap(i1,j);
++i1;
++j;
i2 = k;
std::rotate(i1,j,last);
while (last != j)
{
++j;
++i2;
}
std::rotate(k,i2,last);
return true;
}
}
std::rotate(first,k,last);
return false;
}
然后,您可以繼續執行以下操作:
std::string s = "abcde";
for(std::size_t i = 1; i != s.size(); ++i)
{
do
{
std::cout << std::string(s.begin(),s.begin() + i) << std::endl;
}
while(next_combination(s.begin(),s.begin() + i,s.end()));
}
注意:您應該看到2 ^ n-1個組合,其中n是數組或字符串的長度。
您正在描述一組電源 。 這是一些C ++代碼:
#include <vector>
#include <string>
#include <algorithm>
#include <functional>
using namespace std;
vector< string > string_powerset( string const &in ) {
vector< string > result(1); // start output with one empty string
result.reserve( 1 << in.size() ); // output size = 2^( in.size() )
if ( result.capacity() != 1<<in.size() ) throw range_error( "too big" );
for ( string::const_iterator it = in.begin(); it != in.end(); ++ it ) {
size_t middle = result.size(); // duplicate what we have so far
result.insert( result.end(), result.begin(), result.end() );
// append current character onto duplicated output
for_each( result.begin() + middle, result.end(),
bind2nd( mem_fun_ref( &string::push_back ), * it ) );
}
return result;
}
經過測試的工作:v)。 范圍檢查不是最好的,但無論如何。
由於powerset的指數增長,此代碼將傾向於溢出,因此您應該只傳遞短字符串。 另一個發布的答案通過一次生成並返回一個字符串來避免此問題。 但是,這更容易理解,並且使用更大且更混亂的代碼片段將是過早優化,除非您確實存在溢出問題。
編輯:我寫了一個next_subset
答案 ,它看起來不像本的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.