1. 程式人生 > >lintcode10- String Permutation II- medium

lintcode10- String Permutation II- medium

ray all fin 細節 con medium turn solution 感覺

Given a string, find all permutations of it without duplicates.

Example

Given "abb", return ["abb", "bab", "bba"].

Given "aabb", return ["aabb", "abab", "baba", "bbaa", "abba", "baab"].

函數頭:public List<String> stringPermutation2(String str)

算法:DFS。和排列數字差不多,只是操作對象變了。private void dfs(char[] chars, boolean[] isUsed, StringBuilder sb, List<String> result) 。排序,遞歸函數。每次試著加一個字母,標記被用過,再遞歸。為了去重記得要求如果前後兩個char一樣,而且前面老大沒被用過,那你就不能被加。

細節:1.stringBuilder.deleteCharAT(idx) 可以去除某一位的char(切記是delete不是remove!更有操作小東西的感覺)。2.stringBuilder.length() 直接就是它當前包含的字符串的char數。3.stringBuilder.toString()相當於deepcopy,放心,你這時候照的相不會受之後sb變動而改變。4.初始化數組也要加new關鍵詞啊 int[] a = new int[5]。要是沒有new那還以為你在引用呢。

public class Solution {
    /*
     * @param str: A string
     * @return: all permutations
     
*/ public List<String> stringPermutation2(String str) { // write your code here List<String> result = new ArrayList<>(); if (str == null) { return result; } char[] chars = str.toCharArray(); boolean[] isUsed = new
boolean[chars.length]; // 一定要排序哦 Arrays.sort(chars); dfs(chars, isUsed, new StringBuilder(), result); return result; } private void dfs(char[] chars, boolean[] isUsed, StringBuilder sb, List<String> result) { if (sb.length() == chars.length) { result.add(sb.toString()); return; } for (int i = 0; i < chars.length; i++) { if (isUsed[i]) { continue; } if (i > 0 && chars[i] == chars[i - 1] && !isUsed[i - 1]) { continue; } sb.append(chars[i]); isUsed[i] = true; dfs(chars, isUsed, sb, result); isUsed[i] = false; sb.deleteCharAt(sb.length() - 1); } } }

lintcode10- String Permutation II- medium