算法实现题 2-8 有重复元素的排列问题

360 篇文章 3 订阅
88 篇文章 5 订阅

´问题描述:
设 R={ n
r ,r , ,r 1 2  }是要进行排列的 n 个元素。其中元素 n
r ,r , ,r 1 2  可能相同。试设计
一个算法,列出 R 的所有不同排列。
´编程任务:
给定 n 以及待排列的 n 个元素。计算出这 n 个元素的所有不同排列。
´数据输入:
由文件 input.txt 提供输入数据。文件的第 1 行是元素个数 n,1£n£500。接下来的 1 行
是待排列的 n 个元素。
´结果输出:
程序运行结束时,将计算出的 n 个元素的所有不同排列输出到文件 output.txt 中。文件
最后 1 行中的数是排列总数。
输入文件示例 输出文件示例
input.txt

4
aacc

output.txt

aacc 
acac 
acca 
caac 
caca 
ccaa 
6 
#include<iostream>
#include<string>
#include<algorithm>
#include<bits/stdc++.h>
#include<stack>
#include<set>
#include<vector>
#include<map>
#include<queue>
#include<deque>
#include<cctype>
#include<unordered_set> 
#include<unordered_map> 
#include<fstream>
using namespace std;
map<string,int>mp;
string s;
int n;
ifstream infile("input.txt",ios::in) ;
ofstream outfile("output.txt");
int find(char *list,int k,int m){
	for(int i=k;i<m;i++){
		if(list[i]==list[m]) return 1;
	}
	return 0;
}
void perm(char *list,int k,int m,int &count){
	if(k==m){
		for(int i=0;i<=m;i++){
			outfile<<list[i];
		}
		outfile<<endl;
		count++;
	}
	else{
		for(int i=k;i<=m;i++){
			if(find(list,k,i)==1) continue;
			swap(list[k],list[i]);
			perm(list,k+1,m,count);
			swap(list[k],list[i]);
		}
	}
}
int main(){
	int t=0;
	while(!infile.eof()){
		string x;
		int xx;
		if(!t){
			infile>>xx;
			n=xx;
			t=1;
		}
		else infile>>x;
		s=x;
	} 
	char list[15];
	int count=0;
	for(int i=0;i<s.size();i++){
		list[i]=s[i];
	}
	perm(list,0,n-1,count);
	outfile<<count;
	infile.close();
	outfile.close();
	return 0;
}


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_努力努力再努力_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值