其他分享
首页 > 其他分享> > 剑指Offer 38 字符串的排列

剑指Offer 38 字符串的排列

作者:互联网

  JAVA 回溯解法:

public final String[] permutation(String s) {
        Set<String> reSet = new HashSet<String>();
        search(s, 0, reSet, new StringBuilder(), new HashSet<Integer>());
        return reSet.toArray(new String[reSet.size()]);
    }

    private final void search(String s, int len, Set<String> reSet, StringBuilder sb, Set<Integer> path) {
        if (len == s.length()) {
            String reStr = sb.toString();
            if (!reSet.contains(reStr)) {
                reSet.add(reStr);
            }
            return;
        }
        for (int i = 0; i < s.length(); i++) {
            if (path.contains(i)) {
                continue;
            }
            char currentChar = s.charAt(i);
            path.add(i);
            sb.append(currentChar);
            int nextLen = len + 1;
            search(s, nextLen, reSet, sb, path);
            path.remove(i);
            sb.deleteCharAt(len);
        }
    }

  JS 回溯解法:

var permutation = function (s) {
    let reSet = new Set();
    search(s, 0, reSet, new Array(s.length), "");
    return Array.from(reSet);
};

var search = function (s, len, reSet, path, reStr) {
    if (len == s.length) {
        if (!reSet.has(reStr)) {
            reSet.add(reStr);
        }
        return;
    }
    let nextLen = len + 1;
    for (let i = 0; i < s.length; i++) {
        if (path[i] === 1) {
            continue;
        }
        let currentChar = s.charAt(i);
        path[i] = 1;
        search(s, nextLen, reSet, path, reStr + currentChar);
        path[i] = undefined;
    }
}

 

标签:reSet,search,38,Offer,reStr,len,new,字符串,path
来源: https://www.cnblogs.com/niuyourou/p/13420028.html