zoukankan      html  css  js  c++  java
  • 打印不重复的字符串全排列(递归)

    什么是不重复的字符串全排列,如果是普通字符串全排列,那么

    输入:

    acc

    输出:

    acc
    acc
    cac
    cca
    cca
    cac

    要求写出的去重的,也就是会输出:

    acc
    cac
    cca

    上代码进行比较吧

    import java.io.BufferedInputStream;
    import java.util.HashSet;
    import java.util.Scanner;
    import java.util.Set;
    
    public class test {
    
        public static void arrange1(char[] str, int i) {
            if (i == str.length) {
                System.out.println(str);
            } else {
                for (int j = i; j < str.length; ++j) {
                    swap(str, i, j);
                    arrange1(str, i + 1);
                    swap(str, i, j);
                }
            }
        }
    
        public static void arrange2(char[] str, int i) {
            if (i == str.length) {
                System.out.println(str);
            } else {
                Set<Character> set = new HashSet<Character>(); // 每一层对应一个set
                for (int j = i ; j < str.length; ++j) {
                    if (!set.contains(str[j])) { // 最上面一层的串是起始串,根据起始串思考
                        set.add(str[j]);
                        swap(str, i, j);
                        arrange2(str, i + 1);
                        swap(str, i, j);
                    }
                }
            }
        }
    
        public static void swap(char[] str, int i, int j) {
            char c = str[i];
            str[i] = str[j];
            str[j] = c;
        }
    
        public static void main(String[] args) {
            Scanner cin = new Scanner(new BufferedInputStream(System.in));
            String str = cin.next();
            arrange1(str.toCharArray(), 0);
            System.out.println("======================");
            arrange2(str.toCharArray(), 0);
            cin.close();
        }
    }
    
    ========================================Talk is cheap, show me the code=======================================
    CSDN博客地址:https://blog.csdn.net/qq_34115899
  • 相关阅读:
    外观模式
    解释器模式
    LoadRunner学习笔记(三)
    lr 中cookie的解释与用法
    LR使用web_add_cookie函数进行cookie模拟
    LoadRunner学习笔记(二)
    SVN服务器搭建和使用
    使用Jmeter监测服务器性能指标
    jmeter 使用白皮书
    intellij idea创建maven项目
  • 原文地址:https://www.cnblogs.com/lcy0515/p/9179778.html
Copyright © 2011-2022 走看看