輸出從n開始到1的k個數,
如n=5, k=3;
5 4 3, 5 4 2, 5 4 1, 5 3 2, 5 3 1
4 3 2, 4 3 1, 4 2 1
3 2 1
。。。。。。。。。。。。。。。。。。。。。。
嵌套回圈效率太低了,而且對于任意等的n,k也不好處理。
uj5u.com熱心網友回復:
僅供參考://qplw.cpp
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int v=0;
int w=0;
int m;//記錄字串長度
int n;//記錄字串中的字符種類數
char map[256];//記錄是哪幾種字符
int count[256];//記錄每種字符有多少個
int stack[1000];//遞回用的堆疊,并記錄當前生成的排列
void Make_Map(char *str) {//統計字串的相關資訊
int s[256];
int i;
memset(s,0,sizeof(s));
memset(count,0,sizeof(count));
m=strlen(str);
if (w<1 || m<w) w=m;
while(*str) {
s[*str]++;
str++;
}
n=0;
for (i=0;i<256;i++)
if (s[i]) {
map[n]=i;
count[n]=s[i];
n++;
}
}
void Find(int depth) {//遞回式回溯法生成全排列
if (depth==w) {
int i;
for (i=0;i<depth;i++) putchar(map[stack[i]]);
putchar('\n');
} else {
int i;
if (v && depth>0) {
for (i=0;i<depth;i++) putchar(map[stack[i]]);
putchar('\n');
}
for (i=0;i<n;i++)
if (count[i]) {
stack[depth]=i;
count[i]--;
Find(depth+1);
count[i]++;
}
}
}
void main(int argc,char**argv) {
if (argc<2) {
printf("%s 要產生全排列的字串 [限定長度|-1]\n",argv[0]);
return;
}
if (argc>=3) w=atoi(argv[2]);
if (-1==w) v=1;
Make_Map(argv[1]);
Find(0);
}
//C:\test>qplw
//qplw 要產生全排列的字串 [限定長度|-1]
//
//C:\test>qplw 123
//123
//132
//213
//231
//312
//321
//
//C:\test>qplw 123 2
//12
//13
//21
//23
//31
//32
//
//C:\test>qplw 122333 3
//122
//123
//132
//133
//212
//213
//221
//223
//231
//232
//233
//312
//313
//321
//322
//323
//331
//332
//333
//
//C:\test>qplw 123 -1
//1
//12
//123
//13
//132
//2
//21
//213
//23
//231
//3
//31
//312
//32
//321
//
uj5u.com熱心網友回復:
5 4 3, 5 4 2, 5 3 2,4 3 2這幾個都不是到1,題目自身都有問題,何來解決方案
uj5u.com熱心網友回復:
int* GetNKData(UINT n,UINT k)
{
char* pX=new char[n+1];//申請n+1個位元組,序號0位元組不用,有效位元組1...n
srand( (unsigned)time( NULL ) );
memset(pX,0,n);//位元組值設定為0
for(int i=0;i<k;i++)
{
Retry:
int m=rand()%n+1;
if(pX[m]==1) goto Retry; //這個數已經存在,重來
pX[m]=1;
}
UINT* pVal=new UINT[k];
UINT j=0;
for(int i=1;i<=n,i++)
{
if(pX[i]==1) pVal[j++]=i;
}
delete pX;
return pVal; //呼叫函式記得洗掉這個記憶體
}
uj5u.com熱心網友回復:
memset(pX,0,n);//位元組值設定為0應該改為
memset(pX,0,n+1);//位元組值設定為0
uj5u.com熱心網友回復:
C:\>qplw 54321 3123
124
125
132
134
135
142
143
145
152
153
154
213
214
215
231
234
235
241
243
245
251
253
254
312
314
315
321
324
325
341
342
345
351
352
354
412
413
415
421
423
425
431
432
435
451
452
453
512
513
514
521
523
524
531
532
534
541
542
543
C:\>
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/89641.html
標籤:基礎類
