java 有/无重复字符串的排列组合

package com.learn.huawei;

import java.util.*;

public class RepeatStrArrange {

    static List ans = new ArrayList<>();
    static boolean[] vis ;

    public static void main(String[] args) {
        String[] str = permutation("abc");
        for (String s : str) {
            System.out.print(s+" ");
        }

    }
    public static String[] permutation(String s) {
        char[] cs = s.toCharArray();
        vis = new boolean[cs.length];
        Arrays.sort(cs);
        dfs(cs, "");
        return ans.toArray(new String[ans.size()]);
    }

    public static void dfs(char[] cs, String s){
        if(s.length() == cs.length){
            ans.add(s);
            return ;
        }

        for(int i = 0; i < cs.length; i++){
            if(vis[i]) continue;
            // 剪枝
            if(i > 0 && cs[i] == cs[i - 1] && vis[i - 1]) continue ;
            vis[i] = true;
            dfs(cs, s + cs[i]);
            vis[i] = false;
        }
    }

}

输出:abc acb bac bca cab cba 

你可能感兴趣的:(算法,java,深度优先,开发语言)