find all combinations of a string code example
Example 1: find all permutations of a string
void permute(string a, int l, int r)
{
if (l == r)
cout<<a<<endl;
else
{
for (int i = l; i <= r; i++)
{
swap(a[l], a[i]);
permute(a, l+1, r);
swap(a[l], a[i]);
}
}
}
Example 2: how to print all permutations of a string
void permutation(string s)
{
sort(s.begin(),s.end());
do{
cout << s << " ";
}
while(next_permutation(s.begin(),s.end());
cout << endl;
}
Example 3: combinations in java
private void helper(List<int[]> combinations, int data[], int start, int end, int index) {
if (index == data.length) {
int[] combination = data.clone();
combinations.add(combination);
}
else if (start <= end) {
data[index] = start;
helper(combinations, data, start + 1, end, index + 1);
helper(combinations, data, start + 1, end, index);
}
}