Given an array, print all possible combinations of it's elements. (Note that this would be the equivalent of calling an n-choose-k function n - 1 times where k is 1 on the first call and incremented by one on each subsequent call.) Example:
Input: a b c
Output: a , a b , a b c , a c , b , b c , c
void Combinations(vector<char> &arr)
{
vector<char> res;
CombinationsHelper(arr, res, 0);
}
void CombinationsHelper(vector<char> &arr, vector<char> res, int index)
{
if (index == arr.size())
return;
for (int i = index; i < arr.size(); i++)
{
res.push_back(arr[i]);
for (char c : res)
cout << c;
cout << endl;
CombinationsHelper(arr, res, i + 1);
res.pop_back();
}
} |
|