[劍指offer][第四章][28]字串的排列

yoohoosome發表於2016-04-11

[牛客網]字串測排列

題目理解:題目個給的字串中可能包含重複的字元,你給出的解中也要包含這些重複的字元,但是解集中不應該包含重複的解。

import java.util.ArrayList;
public class Solution {
    public ArrayList<String> Permutation(String str) {
        // 2016-04-11
        ArrayList<String> rst = new ArrayList<String>();
		if (str == null || str.length() == 0) {
            return rst;
        }
        char[] chars = str.toCharArray();
        ArrayList<Character> list = new ArrayList<Character>();
        help(rst, list, chars);
        return rst;
    }
    
    private void help(ArrayList<String> rst, ArrayList<Character> list, char[] leftChars) {
        if (list.size() == leftChars.length) {
            String str = "";
            for (Character each : list) {
                str += each;
            }
            if (!rst.contains(str)) { // 可能導致問題
                rst.add(str);
            }
        }
        
        for (int i = 0; i < leftChars.length; i++) {
        	if (leftChars[i] == 0) {
            	continue;
            }
        	char thisChar = leftChars[i];
            list.add(thisChar);
            leftChars[i] = 0;
            help(rst, list, leftChars);
            list.remove(list.size() - 1);
            leftChars[i] = thisChar;
        }
    }
}


相關文章