(Easy) BackTracking Permutations- Algorithm

Description:

A permutation, also called an “arrangement number” or “order,” is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation.
Source: Mathword(http://mathworld.wolfram.com/Permutation.html)

Below are the permutations of string ABC.
ABC ACB BAC BCA CBA CAB

 

Here is a solution that is used as a basis in backtracking.

 

 

 

Solution: 

class Main {
  public static void main(String[] args) {
    String str = "ABC";
    Main m = new Main();
    m.Permute(str,0,str.length()-1);
         
  }

 public void Permute(String str, int i, int j ){
        
        if(i==j){
              
         System.out.println(str);
        }
        else{
            
            for(int l = i; l<=j; l++){
                
                 str  = swap(str,i,l);
                Permute(str, i+1, j);
                str = swap(str,l,i);
                
            }
            
        }
    }
     public String swap(String a, int i, int j) 
    { 
        char temp; 
        char[] charArray = a.toCharArray(); 
        temp = charArray[i] ; 
        charArray[i] = charArray[j]; 
        charArray[j] = temp; 
        return String.valueOf(charArray); 
    } 


}

  

 

posted @ 2019-08-30 17:36  CodingYM  阅读(153)  评论(0编辑  收藏  举报