28.字符串的排列

来源:互联网 发布:软件著作权 版权 编辑:程序博客网 时间:2024/05/22 17:16

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

解题思路:递归调用;递归算法的四个特性:1.必须可以达到终止条件,否则会陷入死循环;2、子问题在规模上比原问题小;3、子问题可以通过再次递归调用;4、子问题的解可以组成整个问题的解


两步走:第一步,求所有可能出现在第一个位置的字符,即把第一个字符和后面的字符交换

             第二步,固定第一个字符,求后面所有字符的排列,这时候如需要把后面的字符串分成两部分,后面字符串的第一个字符,以及这个字符之后的所有字符,然后回到第一步.......


using System.Collections.Generic;class Solution{    List<string> list=new List<string>();    public List<string> Permutation(string str)    {        // write code here                if(string.ReferenceEquals(str, null) || str.Length == 0){            return list;        }        char[] chars=str.ToCharArray();        SortedSet<string> temp=new SortedSet<string>();        Permutation(chars,0, temp);                list.AddRange(temp);        return list;    }    public void Permutation(char[] chars,int begin,SortedSet<string> list ){        if (chars == null || chars.Length == 0 || begin < 0 || begin> chars.Length - 1)        {            return;        }         if (begin == chars.Length - 1)        {            list.Add(new string(chars));        }        else{            for(int i=begin;i<=chars.Length-1;i++){                swap(chars,begin,i);                Permutation(chars,begin+1,list);                swap(chars,begin,i);            }        }    }    public void swap(char[] chars,int a,int b){        char temp=chars[a];        chars[a]=chars[b];        chars[b]=temp;    }}




0 0
原创粉丝点击