码迷,mamicode.com
首页 > 其他好文 > 详细

(Easy) BackTracking Permutations- Algorithm

时间:2019-08-30 19:35:15      阅读:76      评论:0      收藏:0      [点我收藏+]

标签:img   har   for   out   nbsp   backtrack   ice   char   enc   

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); 
    } 


}

  

技术图片

 

(Easy) BackTracking Permutations- Algorithm

标签:img   har   for   out   nbsp   backtrack   ice   char   enc   

原文地址:https://www.cnblogs.com/codingyangmao/p/11436243.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!