find all combinations of a string code example

Example 1: find all permutations of a string

void permute(string a, int l, int r)  
{  
    // Base case  
    if (l == r)  
        cout<<a<<endl;  
    else
    {  
        // Permutations made  
        for (int i = l; i <= r; i++)  
        {  
  
            // Swapping done  
            swap(a[l], a[i]);  
  
            // Recursion called  
            permute(a, l+1, r);  
  
            //backtrack  
            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()); // std::next_permutation
    
    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);    
  }
}

Tags:

Java Example