69,370
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#include <vector>
#include <algorithm>
using namespace std;
int i;
int L;
void main(int argc,char **argv) {
if (argc<2) {
printf("%s 要排列的字符串\n",argv[0]);
return;
}
L=strlen(argv[1]);
vector<char> P(L);
vector<char>::iterator b,e,it;
b=P.begin();
e=P.end();
for (i=0;i<L;i++) P[i]=argv[1][i];
sort(b,e);
i=0;
do {
printf("%10d: ",++i);
for(it=b;it!=e;it++) printf("%c",*it);
printf("\n");
} while (next_permutation(b,e));
printf("The total: %d",i);
}
第i个位置的数字为x,则第i+1个位置的数字必须大于等于2x。
0 , 0 1 2 3 4 5 6 7 8 9
1 , 2 3 4 5 6 7 8 9
2 , 4 5 6 7 8 9
3 , 6 7 8 9
4 , 8 9
5 ,
6 ,
7 ,
8 ,
9 ,
#define N 10 //从[1, N]中取数
#define M 3 //从[1, N]中取M个数
int a[M] = {0}; //保存临时序列,用于输出
int count = 0; //取了多少个数字
//从[s, n]中取m个数
void Permutation(int n, int m, int s)
{
int i;
if(0 == m)
{
total++;
printf("排列%d:\t",total);
for(i=0; i<M; i++)
{printf("%d ", a[i]);} //输出序列
printf("\n");
return;
}
int temp = 1 <<(m-1);
int maxval = n/temp;
for(i=s; i<=maxval; i++)
{
a[count++] = i;
Permutation(n, m-1, i*2);
count--;
}
}
[/quote]
你把N值改到1000或者更大再试下,把m值在适当的调整一下,就可以看出来了缺陷了。[/quote]
你难道没发现我两的算法本质是一致的!要说有问题,两者都存在的,只不过我的上限要比你小而已.
#define N 10 //从[1, N]中取数
#define M 3 //从[1, N]中取M个数
int a[M] = {0}; //保存临时序列,用于输出
int count = 0; //取了多少个数字
//从[s, n]中取m个数
void Permutation(int n, int m, int s)
{
int i;
if(0 == m)
{
total++;
printf("排列%d:\t",total);
for(i=0; i<M; i++)
{printf("%d ", a[i]);} //输出序列
printf("\n");
return;
}
int temp = 1 <<(m-1);
int maxval = n/temp;
for(i=s; i<=maxval; i++)
{
a[count++] = i;
Permutation(n, m-1, i*2);
count--;
}
}
[/quote]
你把N值改到1000或者更大再试下,把m值在适当的调整一下,就可以看出来了缺陷了。
#define N 10 //从[1, N]中取数
#define M 3 //从[1, N]中取M个数
int a[M] = {0}; //保存临时序列,用于输出
int count = 0; //取了多少个数字
//从[s, n]中取m个数
void Permutation(int n, int m, int s)
{
int i;
if(0 == m)
{
total++;
printf("排列%d:\t",total);
for(i=0; i<M; i++)
{printf("%d ", a[i]);} //输出序列
printf("\n");
return;
}
int temp = 1 <<(m-1);
int maxval = n/temp;
for(i=s; i<=maxval; i++)
{
a[count++] = i;
Permutation(n, m-1, i*2);
count--;
}
}
//这个算法的大致意思是先循环第一位可能的数字,再根据第一位的数字循环第二位可能出现的数字,以此类推。
__int64 Func(int n, int m, int iMinNum)
{
if (m == 1)
{
return (__int64)(n - iMinNum + 1);
}
__int64 iRet = 0;
int i = 0;
for (i = iMinNum; i <= n/(1 << (m-1)); i++)
{
iRet += Func(n, m-1, i*2);
}
return iRet;
}
[/quote]
很可惜。我说的动态规划和你写的这个完全不是一回事。不懂什么是dp就别乱总结。//这个算法的大致意思是先循环第一位可能的数字,再根据第一位的数字循环第二位可能出现的数字,以此类推。
__int64 Func(int n, int m, int iMinNum)
{
if (m == 1)
{
return (__int64)(n - iMinNum + 1);
}
__int64 iRet = 0;
int i = 0;
for (i = iMinNum; i <= n/(1 << (m-1)); i++)
{
iRet += Func(n, m-1, i*2);
}
return iRet;
}