27. 字符串的排列

题目描述

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

输入描述:

输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。
// 27_strPermutation.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"


#include <stdlib.h>
#include <string>
#include <stdio.h>
#include <iostream>
#include <vector>
#include <stack>
#include <queue>
#include <algorithm>
 
using namespace std;
 
class Solution {
public:
    vector<string> Permutation(string str) {
        vector<string> res;
        if(str.size()){
            string tmpres = "";
            StrPermutation(str, res, tmpres, 0);
        }
        return res;
    }
    void StrPermutation(string str, vector<string> &res, string &tmpres, int start)
    {
        if(start == str.size()){
            res.push_back(tmpres);
            return;
        }
        for(int i = start; i < str.size(); ++ i)
        {
            if(i != start && str[i] == str[start])//i与start位置的数字相同,则不交换
                continue;
            char tmp = str[i];
            str[i] = str[start];
            str[start] = tmp;
            tmpres += str[start];
            StrPermutation(str, res, tmpres, start + 1);
            tmpres.pop_back();
        }
    }
};
 
int main(void)
{
	string str("abcd");
	Solution s;
	vector<string> v;
	int i = 0;
 
	v = s.Permutation(str);
	for(i = 0; i < v.size(); i++)
	{
		cout << v[i] << endl;
	}
	
	
	return 0;
}



猜你喜欢

转载自blog.csdn.net/weixin_39605679/article/details/80915208