码迷,mamicode.com
首页 > 其他好文 > 详细

Find all the permutations of a string

时间:2016-01-23 07:57:10      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:

就是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

标签:

原文地址:http://www.cnblogs.com/hygeia/p/5152781.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!