今天做了poj1270这道题,采用了深度优先搜索,确实启发了我,无意中想了一个这么一个问题:求数组中任意n个数的全排列是不是也可以用深度优先去搜索(我理解这是一种深度搜索,不知道对不对)。
代码如下:
#include
#include
using namespace std;
#define MAX 20
vectorindex;
int visited[MAX]={0};
void dfs(int arr[],int len,int num,int k)//len代表数组长度,num表示当前求到第几个,k表示多少数的全排列
{
if(k==num){
for(int i=0;i
如果是组合排列又该如何呢,容我思考思考。
恩,想了一会儿,调试了一下,如果是组合应该是这样的:
#include
#include
using namespace std;
vector ivec;
void zuhe(int arr[],int n,int num,int k)//n表示当前搜索的索引,num表示搜索到第几个数,k表示多少个数的排列
{
if(n::iterator it;
for(it=ivec.begin();it!=ivec.end();++it)
cout<<*it<<" ";
cout<
可以这样:
#include
#include
using namespace std;
int arr[] = {1,2,3,4,5,6,7,8,9,10};
int len = 10 , m = 3;
void dfs(int index , int num , vector &vec)
{
int i ;
if(index == len+1)
return ;
if(num == 0)
{
static int k = 1 ;
cout<vec;
dfs(0 , m , vec);
system("pause");
return 0;
}
注:组合和排列的区别就是没有了回溯过程,但这是一种什么样的搜索算法呢(有关类似的解法还可以参见博客求数组中和为sum中的数http://blog.csdn.net/u010064842/article/details/8754428),不得而知,菜鸟依旧是菜鸟。
下面贴一下海涛关于全排列的代码:http://zhedahht.blog.163.com/blog/static/254111742007499363479
void Permutation(char* pStr, char* pBegin)
{
if(!pStr || !pBegin)
return;
// if pBegin points to the end of string,
// this round of permutation is finished,
// print the permuted string
if(*pBegin == '\0')
{
printf("%s\n", pStr);
}
// otherwise, permute string
else
{
for(char* pCh = pBegin; *pCh != '\0'; ++ pCh)
{
// swap pCh and pBegin
char temp = *pCh;
*pCh = *pBegin;
*pBegin = temp;
Permutation(pStr, pBegin + 1);
// restore pCh and pBegin
temp = *pCh;
*pCh = *pBegin;
*pBegin = temp;
}
}
}
如果打印的数允许重复,且为全排列:例如,000,001,002,003
#include
#include
#include
#include
#include
using namespace std;
int arr[] = {0,1,2,3,4,5,6,7,8,9};
int len = 10 , m = 3;
void dfs(int num , vector& vec , int curnum )
{
int i ;
if(curnum == num)
{
static int k = 1 ;
cout<vec;
dfs(m , vec , 0 );
system("pause");
return 0;
}
下面是海涛上面的一道题,可以用我的解法来做,也可以用海涛的代码来做,思路是一样的。(题目连接:http://zhedahht.blog.163.com/blog/static/2541117420114172812217/)
题目:输入一个字符串,输出该字符串中字符的所有组合。举个例子,如果输入abc,它的组合有a、b、c、ab、ac、bc、abc。
void Combination(char* string)
{
if(string == NULL)
return;
int length = strlen(string);
vector result;
for(int i = 1; i <= length; ++ i)
Combination(string, i, result);
}
void Combination(char* string, int number, vector& result)
{
if(number == 0)
{
vector::iterator iter = result.begin();
for(; iter < result.end(); ++ iter)
printf("%c", *iter);
printf("\n");
return;
}
if(*string == '\0')
return;
result.push_back(*string);
Combination(string + 1, number - 1, result);
result.pop_back();
Combination(string + 1, number, result);
}