【剑指offer】字符串的排列(字符串)

版权声明:本文为原创博客,未经允许,请勿转载。 https://blog.csdn.net/u013095333/article/details/88599698

题目描述

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

输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。

链接

https://www.nowcoder.com/practice/fe6b651b66ae47d7acce78ffdd9a96c7?tpId=13&tqId=11180&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

代码

class Solution {
public:
    vector<string> Permutation(string str) {
        vector<string> ans;
        if(str.length() == 0){
        	return ans;
        }
        getAns(ans, str, 0);
        sort(ans.begin(), ans.end());
        return ans;
    }
    void getAns(vector<string>& ans, string s, int index){
    	if(index == s.length() - 1){
    		ans.push_back(s);
    	}
    	else{
    		for(int i = index; i < s.length(); i++){
    			string stemp = s;
				if(i!=index && stemp[index] == stemp[i]){
					continue;
				}
    			swap(stemp[index], stemp[i]);
    			getAns(ans, stemp, index+1);
    		}
    	}
    }  
};

猜你喜欢

转载自blog.csdn.net/u013095333/article/details/88599698