【LeetCode】面试题38. 字符串的排列(JAVA)

原题地址:https://leetcode-cn.com/problems/zi-fu-chuan-de-pai-lie-lcof/

题目描述:
在这里插入图片描述
解题方案:
开始用的普通回溯,set去重,而且用的是StringBuilder,但是复杂度比较高。优化是改用了交换法回溯,节省空间,并且用char数组操作也更快,去重改用了标记数组,比set更快,但这道题是只有小写字母,如果还有其他字符的话标记数组就不能使用了。

代码:
交换法:

class Solution {
    List<String> res;
    char[] ans;
    public String[] permutation(String s) {
        res = new ArrayList<>();
        ans = s.toCharArray();
        DFS(s, 0, 0, ans);
        
        return res.toArray(new String[res.size()]);
    }

    void DFS(String s, int size, int start, char[] ans)
    {
        int len = s.length() - 1;
        if(start == len)
        {
            res.add(new String(ans));
            return;
        }
        boolean[] visited = new boolean[26];

        for(int i = start; i <= len; i ++)
        {
            if(visited[ans[i] - 'a'] == false)
            {
                visited[ans[i] - 'a'] = true;
                swap(start, i);
                DFS(s, size + 1, start + 1, ans);
                swap(i, start);
            }
        }
    }

    void swap(int a, int b)
    {
        char tmp = ans[a];
        ans[a] = ans[b];
        ans[b] = tmp;
    }
}

普通回溯:

class Solution {
    Set<String> res;
    StringBuilder ans;
    public String[] permutation(String s) {
        res = new HashSet<>();
        // if(s.length() == 0) return new String[""];
        ans = new StringBuilder(s);
        DFS(s, 0, 0, ans);
        
        return res.toArray(new String[res.size()]);
    }

    void DFS(String s, int size, int start, StringBuilder ans)
    {
        int len = s.length() - 1;
        if(start == len)
        {
            res.add(new StringBuilder(ans).toString());
            return;
        }
        for(int i = start; i <= len; i ++)
        {
            swap(start, i);
            DFS(s, size + 1, start + 1, ans);
            swap(i, start);
        }
    }

    void swap(int a, int b)
    {
        char tmp = ans.charAt(a);
        ans.setCharAt(a, ans.charAt(b));
        ans.setCharAt(b, tmp);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值