字符全排列算法及原理

研究一下全排列算法,他奶奶的,我一看见递归我就晕,研究了许久还是有点模糊。慢慢来吧,数学太差了。

先贴上代码,省得以后用到的时候又忘了,希望对大家有帮助。

 

package pailie;

import java.io.*;
import java.util.*;

public class PaiLie {
    
public PaiLie() {
    }

    
public static void main(String[] args) {
        PaiLie p 
= new PaiLie();

        
while (true) {
            Scanner r 
= new Scanner(System.in);
            String s 
= r.nextLine();

            
if (s.equals("exit")) {
                System.out.println(
"bye bye...");
                
break;

            }
            System.out.println(
"开始排列字符串"" + s + """);
            p.paiLie(s);

        }
    }

    
public void paiLie(String s) {
        
int t = s.length();
        
char[] charA = new char[t];
        
for (int i = 0; i < t; i++) {
            charA[i] 
= s.charAt(i);

        }
        pl(charA, 
0);

    }

    
private void pl(char[] ca, int deep) {
        
int t = ca.length;
        
int d = deep;
        
if (d == t - 1) {
            System.out.println(ca);
            
return;
        }
        
for (int i = deep; i < t; i++) {

            
char temp = ca[deep];
            ca[deep] 
= ca[i];
            ca[i] 
= temp;
            pl(ca, deep 
+ 1);
            ca[i] 
= ca[deep];
            ca[deep] 
= temp;

        }

    }


}

原理:  
  1   2   3   4   5  
  deep   =   0  
先用1     1,2,3,4,5   交换位置,排列为  
  |  
  |  
  V  
  1,2,3,4,5  
  2,1,3,4,5  
  3,2,1,4,5  
  4,2,3,1,5  
  5,2,3,4,1  
   
 
然后对每一个排列在从第二个位置开始重复上面的过程,以3,2,1,4,5为例:   
         deep   =   1   
                   |   
                   |   
                   V  
  2--2
交换:3,2,1,4,5  
  2--1
交换:3,1,2,4,5  
  2--4
交换:3,4,1,2,5  
  2--5
交换:3,5,1,4,2  
   
 
再以3,4,1,2,5为例:   
            deep=2     
                     |   
                     |   
                     V  
  1--1
交换:3,4,1,2,5  
  1--2
交换:3,4,2,1,5  
  1--5
交换:3,4,5,2,1  
   
 
3,4,5,2,1为例:   
                  deep=3   
                            |   
                            |   
                            V  
  2--2
交换:3,4,5,2,1  
  2--1
交换:3,4,5,1,2  
   
 
3,4,5,1,2为例:   
                         deep=4   
                             |   
                             |   
                            V  
  2--2
交换:3,4,5,1,2  
   
  deep=5  
  print_it;  
  return;

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值