• lintcode10- String Permutation II- medium


    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);
            }
            
        }
    }
  • 相关阅读:
    关于jsp
    NASA: A Closer View of the Moon(近距离观察月球)
    NASA: Seeing Jupiter(注视木星)
    NASA: SpaceX的猎鹰9号火箭将龙飞船发射到国际空间站
    导航狗IT周报第十五期(July 8, 2018)
    导航狗IT周报-2018年05月27日
    导航狗IT周报-2018年05月18日
    小苹果WP(实验吧-隐写术)
    Python实现猜数字游戏1.0版
    代码方式设置WordPress内所有URL链接都在新标签页打开
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/7782182.html
Copyright © 2020-2023  润新知