字符串的排列

来源:互联网 发布:一个能看网络攻击网站 编辑:程序博客网 时间:2024/06/15 01:02

题目描述
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
输入描述:
输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。

解题思路:交换第一个位置的字符和其他位置的字符,然后递归添加结果。
一刷ac

递归

import java.util.ArrayList;import java.util.HashSet;import java.util.Collections;public class Solution {    public ArrayList<String> Permutation(String str) {        ArrayList<String> res = new ArrayList<String>();        HashSet<String> set = new HashSet<String>();        if(str == null || str.length() == 0) return res;        if(str.length() == 1){            res.add(str);            return res;        }        for(int i = 0; i < str.length(); i++){            String newstr = str.substring(0, i) + str.substring(i+1, str.length());            ArrayList<String> tmp = Permutation(newstr);            for(String s : tmp) set.add(str.charAt(i)+s);        }        for(String s : set) res.add(s);        Collections.sort(res);        return res;    }}
import java.util.ArrayList;import java.util.HashSet;import java.util.Collections;public class Solution {    public ArrayList<String> Permutation(String str) {        ArrayList<String> res = new ArrayList<String>();        if(str == null || str.length() == 0) return res;        char[] arr = str.toCharArray();        dfs(arr, 0, res);        Collections.sort(res);        return res;    }    public void dfs(char[] str, int index, ArrayList<String> res){        if(index == str.length - 1){            res.add(new String(str));        }        for(int i = index; i < str.length; i++){            if(i == index || str[i] != str[index]){                swap(str, i, index);                dfs(str, index+1, res);                swap(str, i, index);            }        }    }    public void swap(char[] str, int i, int j){        char ch = str[i];        str[i] = str[j];        str[j] = ch;    }}
0 0
原创粉丝点击