全排列递归(搜索)以及库函数的应用 递归例题poj1731

60 篇文章 0 订阅
42 篇文章 0 订阅

第一种方法是用递归:多次调用函数可能会时间比较长,所以建议用库函数而不是递归

这里可以当做一个搜索来理解

五位数:当做数组来处理就好理解了

#include <stdio.h>
#include <string.h>

int array[10];
bool used[10];

const int n=5;

void print()
{
	for(int i=1;i<=n;i++)
		printf("%d",array[i]);
	puts("");
}

void dfs(int index)
{
//-------------递归基--------------//
	if(index==n+1){
		print();
		return ;
	}
//--------------搜索---------------//
	for(int i=1;i<=n;i++)
		if(!used[i]){
			array[index]=i;
			used[i]=true;
			dfs(index+1);
			//下面是回溯
			used[i]=false;
		}
}

int main()
{
	//freopen("out.txt","w",stdout);
	memset(used,false,sizeof(used));
	dfs(1);
	return 0;
}


c++没有c好

#include <iostream>
#include <algorithm>
#include <string>

using namespace std;

int main()
{
    string str;
    cin >> str;
    sort(str.begin(), str.end());
    cout << str << endl;
    while (next_permutation(str.begin(), str.end()))
    {
        cout << str << endl;
    }
    return 0;
}


c代码

#include <cstdio>
#include <algorithm>
#include <cstring>
#define MAX 100

using namespace std;

int main()
{
    int length;
    char str[MAX];
    gets(str);
    length = strlen(str);
    //注意***需要排序
    sort(str, str + length);
    puts(str);
    while (next_permutation(str, str + length))
    {
        puts(str);
    }
    return 0;
}


例题:

题目意思就是排序,但是有相同的不能重复出现


#include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;

char a[205];
bool used[205];
char str[205];
int len;

void dfs(int index)
{
    char last='\0';//不是全局变量(保证每一层相邻如果相同就不进行下去的,而不是全局变量)
    if(index==len){
        str[len]='\0';
        puts(str);
        return ;
    }

    for(int i=0;i<len;i++){
        if(!used[i]&&a[i]!=last){//这里我的思路就是相邻的两个相同的就不能够递归下去,防止了相同的序列出现
            str[index]=a[i];//注意是index,不是i,之前就是这个错误
            used[i]=true;
            last=a[i];
            dfs(index+1);
            used[i]=false;
        }
    }

}

int main()
{
    while(gets(a))
    {
        len=strlen(a);
        memset(used,false,sizeof(used));
        sort(a,a+len);
        dfs(0);
    }
    return 0;
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值