牛客-剑指offer系列题解:字符串的排列

记录刷题的过程。牛客和力扣中都有相关题目,这里以牛客的题目描述为主。该系列默认采用python语言。

1、问题描述:
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。

2、数据结构:
字符串

3、题解:
可以和567 字符串的排列一起做
在这里插入图片描述
上图选自https://leetcode-cn.com/problems/zi-fu-chuan-de-pai-lie-lcof/solution/mian-shi-ti-38-zi-fu-chuan-de-pai-lie-hui-su-fa-by/

-*- coding:utf-8 -*-
class Solution:
    def Permutation(self, ss):
        # write code here
        c,res = list(ss),[]
        #dfs
        def dfs(depth):
            #返回条件
            if depth == len(c) -1:
                res.append(''.join(c))
                return
            dic = set()
            for i in range(depth,len(c)):
                if c[i] in dic:
                    continue
                dic.add(c[i])
                c[i],c[depth] = c[depth],c[i]
                dfs(depth + 1)
                c[i],c[depth] = c[depth],c[i]
        dfs(0)
        return res

或者:

class Solution:
    def Permutation(self, ss):
        # write code here
        if not ss: return []
        s = list(sorted(ss))
        res = []

        def helper(s, tmp):
            if not s: res.append(''.join(tmp))
            for i, char in enumerate(s):
                if i > 0 and s[i] == s[i - 1]:
                    continue
                helper(s[:i] + s[i + 1:], tmp + [char])

        helper(ss, [])
        return res

另外有数组的全排列:

class Solution:
    def permuteUnique(self, nums: List[int]) -> List[List[int]]:
        res=[]
        nums.sort()
        def helper(nums,temp):
            if not nums:
                res.append(temp)
            for i in range(len(nums)):
                if i>0 and nums[i]==nums[i-1]:
                    continue
                helper(nums[:i]+nums[i+1:],temp+[nums[i]])
        helper(nums,[])
        return res
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值