排列的字典序问题(Java)

在这里插入图片描述
思想:前缀法求字典序全排列,count计数,对比是否等于输入的排列,等于则打印count,并且输入下一个字典序的全排列。

import java.util.Arrays;
import java.util.Scanner;

public class Permutation1 {
    static int count = 0, temp = 0 ;
    static boolean flag = false ;
    public static boolean check(String prefix, char [] arr, char c){//c在前缀中的个数要小于在数组中的个数才能递归
        int sum1 = 0, sum2 = 0 ;
        for(int i=0; i<prefix.length(); i++){
            if(c == prefix.charAt(i)){
                sum1 ++ ;
            }
        }
        for(int j=0; j<arr.length; j++){
            if(c == arr[j]){
                sum2 ++ ;
            }
        }
        if(sum2 > sum1){
            return true ;
        }else{
            return false ;
        }
    }
    public static void permutation(String prefix, char [] arr, char [] t){ //求全排列
        if(prefix.length() == arr.length){
           if(prefix.equals(String.valueOf(t).trim())) { //找出与输入字符相等的输出为字典序全排列第几个
               flag = true ;
               temp = count ;
               System.out.println(count);
           }
            if(temp+1 == count && flag){ //输出下一个
                for(int i=0; i<prefix.length(); i++){
                   System.out.print(prefix.charAt(i) + " ");
                }
            }
            count ++ ;
            return ;
        }
        for(int i=0; i<arr.length; i++){
            char c = arr[i] ;
            if(check(prefix, arr, c))
                permutation(prefix+c, arr, t);
        }
    }
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int n = input.nextInt();
        char[] c = new char[n];
        char[] t = new char[n] ;
        for (int i = 0; i < n; i++) {
            c[i] = input.next().charAt(0);
            t[i] = c[i] ;
        }
        Arrays.sort(c) ;
        permutation("", c, t);
    }
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

nuist__NJUPT

给个鼓励吧,谢谢你

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值