Prove safety offer: string arrangement (java)

Title: Enter a string, arranged to print all of the characters in the string.

For example input string abc, the characters printed by a, b, c can be arranged out of all strings: abc, abc, bac, bca, cab, cba

  We seek the entire string arrangement can be viewed as two steps: First, determine all possible character in the first position, i.e., all the characters in the first character and later exchange. A second step of fixing the first character, seeking arrange all of the following character. This time we still put all the characters back into two parts: The first character after character, and all characters after the character. Then one by one the first character and the characters following it ...... exchange

      
    public void swap(char[] arr,int idx1,int idx2){  
        char temp = arr[idx1];  
        arr[idx1] = arr[idx2];  
        arr[idx2] = temp;  
    }  
    public void permutation(char[] arr,int index,int size){  
        if(index == size){  
            for(int i = 0;i<arr.length;i++){  
                System.out.print(arr[i]+ "");  
            }  
            System.out.println();  
        }  
        else{  
            for(int i = index;i<size;i++){                
                swap(arr,i,index);    //我们从index向后扫描每一个字符(即指针i指向的字符),交换index和i指向的字符 
                permutation(arr,index+1,size);  //对index后面的字符数组递归地做排列操作  
                swap(arr,i,index);  //每次递归固定要排列字符数组第一个字符不变
            }  
        }  
    } 


Published 118 original articles · won praise 35 · views 120 000 +

Guess you like

Origin blog.csdn.net/abc7845129630/article/details/52729835