元素:abc以这种方式的所有组合:
a
b
c
ab
ac
bc
abc
在没有重复的情况下获得唯一元素组合总数的公式= 2 ^ n-1(其中n是唯一元素的数量)
在我们的示例中:2 ^ 3-1-7 =
另一个获得特定长度组合的公式= n!/(r!*(n-r)!)(其中n = nb个唯一项且r = length)
以上情况的示例r = 2:3!/(2!* 1!)= 3这是ab ac bc
是否有任何算法或函数可以获取所有7种组合?我进行了很多搜索,但我所能找到的只是一种具有特定长度的组合。
更新:
这是我到目前为止所拥有的,但是只能与特定长度结合使用:
void recur(string arr[], string out, int i, int n, int k, bool &flag)
{
flag = 1;
// invalid input
if (k > n)
return;
// base case: combination size is k
if (k == 0) {
flag = 0;
cout << out << endl;
return;
}
// start from next index till last index
for (int j = i; j < n; j++)
{
recur(arr, out + " " + arr[j], j + 1, n, k - 1,flag);
}
}
我找到的解决该问题的最佳算法是使用按位运算符。您只需要开始以二进制计数。二进制数字1表示您必须显示数字。
例如
如果是字符串“ abc”
number , binary , string
1 , 001 , c
2 , 010 , b
3 , 011 , bc
4 , 100 , a
5 , 101 , ac
6 , 110 , ab
7 , 111 , abc
这是我找到的最好的解决方案。您可以简单地通过循环来完成。不会有任何内存问题。
这是代码
#include <iostream>
#include <string>
#include <math.h>
#include<stdio.h>
#include <cmath>
using namespace std;
int main()
{
string s("abcd");
int condition = pow(2, s.size());
for( int i = 1 ; i < condition ; i++){
int temp = i;
for(int j = 0 ; j < s.size() ; j++){
if (temp & 1){ // this condition will always give you the most right bit of temp.
cout << s[j];
}
temp = temp >> 1; //this statement shifts temp to the right by 1 bit.
}
cout<<endl;
}
return 0;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句