2018-03-18更新
题目描述
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
输入描述:
输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。
进行一些算法总结:
1、递归的方法,基于回溯法,dfs
class Solution {
public:
void permString(vector<string> &res, int index, string str){
if(index == str.size() - 1)
res.push_back(str);
for(int i = index; i < str.size(); ++i){
if(i != index && str[index] == str[i])
continue;
swap(str[i], str[index]);
permString(res, index + 1, str);
}
}
vector<string> Permutation(string str) {
sort(str.begin(), str.end());
vector<string> res;
permString(res, 0, str);
return res;
}
};
2、字典生成算法
class Solution {
public:
void selfReverse(string &str, int index){
int len = str.size();
if(len == 0 || len <= index)
return;
for(int i = 0; i < (len - index)/2; ++i)
if(index + i != len - i - 1)
swap(str[index + i], str[len - i - 1]);
}
vector<string> Permutation(string str) {
vector<string> res;
if(str.size() != 0){
sort(str.begin(), str.end());
res.push_back(str);
int len = str.size();
while(true){
int front = len - 1, back;
while(front >= 1 && str[front - 1] >= str[front])
front--;
if(front == 0) break;
back = front;
front--;
while(back < len && str[front] < str[back])
back++;
back--;
swap(str[front], str[back]);
selfReverse(str, front + 1);
res.push_back(str);
}
}
return res;
}
};
3、利用stl
vector<string> Permutation(string str){
vector<string> answer;
if(str.empty())
return answer;
sort(str.begin(),str.end());
do{
answer.push_back(str);
}while(next_permutation(str.begin(),str.end()));
return answer;
}
---------------------------------------------------------------------------------------------------------------------------------
题目:
对于1到n的一个全排列,可以根据中间的大小关系插入合适的大于小于符号即‘>’和‘<’, 使其成为一个合法的不等式数列,
但是只有k个小于号和n-k-1个大于号,请问1-n的任意排列情况中总共有多少种排列可以实现合法不等式数列?
例:n=3,k=1
输出为4:
1<3>2, 3>1<2, 2>1<3, 2<3>1
C++代码:
#include <iostream>
using namespace std;
int n, k,res = 0;
int check(int a[], int len){
int tk = 0;
for(int i = 0; i<len-1; i++){
if(a[i] < a[i+1])
tk++;
}
if(tk == k)
return 1;
else
return 0;
}
void swap(int *a ,int *b)
{
int m ;
m = *a;
*a = *b;
*b = m;
}
void perm(int list[],int head, int end )
{
int i;
if(head >end)
{
if(check(list,n))
res++;
}
else
{
for(i = head ; i <=end;i++)
{
swap(&list[head],&list[i]);
perm(list,head+1,end);
swap(&list[head],&list[i]);
}
}
}
int main(){
cin>>n>>k;
int a[n];
for(int i = 0; i<n; i++){
a[i] = i + 1;
}
perm(a,0,n-1);
cout<<res;
return 0;
}