字符串的排列

题目

描述
输入一个长度为 n 字符串,打印出该字符串中字符的所有排列,你可以以任意顺序返回这个字符串数组。
例如输入字符串ABC,则输出由字符A,B,C所能排列出来的所有字符串ABC,ACB,BAC,BCA,CBA和CAB。
数据范围:n<10
要求:空间复杂度 O(n!),时间复杂度 O(n!)
输入描述:
输入一个字符串,长度不超过10,字符只包括大小写字母。

思路

采用深度优先搜索的思想来解决全排列的问题,深度优先搜索有两种状态,一种是当前状态,一种是可选状态。不断更新当前状态和可选状态。
如abc
[] [abc]
[a][bc]
[b][c]
[c][b]

[b][ac]
[a][c]
[c][a]

[c][ab]
[a][b]
[b][a]

代码

python代码:

#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param str string字符串 
# @return string字符串一维数组
#
class Solution:
    res = []
    def Permutation(self , str: str) -> List[str]:
        # write code here
        curr = ""
        store = str
        self.dfs(curr, store)
        return self.res

    def dfs(self, curr, store):
        if not len(store):
            self.res.append(curr)
            return
        for i in range(len(store)):
            if(i>0 and store[i]==store[i-1]):
                continue
            self.dfs(curr+store[i], store[0:i]+store[i+1:])

c++代码

class Solution {
public:
    vector<string> res;
    int n;
    vector<string> Permutation(string str) {
        this->n = str.size();
//         sort(str.begin(), str.end());
        string curr = "";
        string store = str;
        dfs(curr, store);
        return res;
    }
    
    void dfs(string curr, string store){
        //curr表示当前状态,store表示可选状态
        //1、是否满足条件,返回结果
        //2、判断终止条件
        //3、继续搜索
        if(store.empty()){
            return res.push_back(curr);
        }
        for(int i=0; i<store.size(); i++){
            //去重
            if(store[i]==store[i-1]){
                continue;
            }
            int len = store.size();
            dfs(curr+store[i], store.substr(0,i)+store.substr(i+1,len));
        }
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

超超爱AI

土豪请把你的零钱给我点

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值