next_permutation若返回false,则将数组置为字典序最小值。
#include <cstdio> #include <algorithm> using namespace std; char samp[] = {'1', '2', '3', '4', '5', '6', '7', '8', '9'}; char str[10]; int main(){ int t, n, m, i; scanf("%d", &t); while(t--){ scanf("%d%d", &n, &m); do{ if(!equal(samp, samp + m, str)){ copy(samp, samp + m, str); for(i = 0; i < m; ++i) putchar(str[i]); putchar('\n'); } }while(next_permutation(samp, samp + n)); } return 0; }
800707 | 长木 | 擅长排列的小明 | Accepted | 32 | 232 | C/C++ | 04-07 16:25:32 |
方法二:DFS
#include <stdio.h> #include <string.h> int n, m, id; bool arr[10]; int store[10]; void print(){ for(int i = 1; i <= m; ++i) printf("%d", store[i]); printf("\n"); } void DFS(){ if(id == m){ print(); return; } for(int i = 1; i <= n; ++i){ if(!arr[i]){ store[++id] = i; arr[i] = 1; DFS(); --id; arr[i] = 0; } } } int main(){ int t; scanf("%d", &t); while(t--){ scanf("%d%d", &n, &m); DFS(); memset(arr, 0, sizeof(arr)); id = 0; } return 0; }