Find all the permutations of a string

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Find all the permutations of a string相关的知识,希望对你有一定的参考价值。

就是permutations II考虑有重复字母的情况。

String str = "someString";
char[] charArray = str.toCharArray();

对char array进行排序:

Arrays.sort(charArray) 

之后再把CharArray转化成string

char[] myString = new char[] {‘T‘, ‘H‘, ‘I‘, ‘S‘, ‘ ‘,  ‘I‘, ‘S‘, ‘ ‘, ‘T‘, ‘E‘, ‘S‘, ‘T‘};

String output1 = new String(myString);

 

permutation II 的代码

public class Solution {
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        Arrays.sort(nums);
        LinkedList<Integer> list = new LinkedList<Integer>();
        for (int num : nums) list.add(num);
        perm(list, 0, res);
        return res;
    }
    private void perm(LinkedList<Integer> nums, int start, List<List<Integer>> res){
        if (start == nums.size() - 1){
            res.add(new LinkedList<Integer>(nums));
            return;
        }
        for (int i = start; i < nums.size(); i++){
            if (i > start && nums.get(i) == nums.get(i - 1)) continue;
            nums.add(start, nums.get(i));
            nums.remove(i + 1);
            perm(nums, start + 1, res);
            nums.add(i + 1, nums.get(start));
            nums.remove(start);
        }
    }
}

 

以上是关于Find all the permutations of a string的主要内容,如果未能解决你的问题,请参考以下文章

UVA11077 Find the Permutations

Uva 11077 Find the Permutation

[JavaScript 刷题] 找到所有的排列顺序 (Find All Permutation)

Uva 11077 Find the Permutations [置换群 DP]

1. PermMissingElem Find the missing element in a given permutation.

[Algorithm] A nonrecursive algorithm for enumerating all permutations of the numbers {1,2,...,n}(代码片