http://poj.org/problem?id=3187
/*总结:头文件#include <algorithm>, next_permutation(num,num+n)生成数组num的全排列, */ #include <iostream> #include <algorithm> using namespace std; int fun(int *num,int n) { int num1[10];//不能直接使用num操作,涉及内存管理,需要用替换数组进行操作 for(int i = 0;i < n;i++) num1[i] = num[i]; for(int i = 1;i <= n-1;i++) { int x = 0; for(int j = 0;j < n - i;j++) { num1[x++] = num1[j]+num1[j+1]; } } return num1[0]; } int main(int argc, char *argv[]) { int n,finalSum,num[1001]; while(cin >> n >> finalSum) { for(int i = 0;i < n;i++) num[i] = i+1; int sum,cnt = 1; do { sum = fun(num,n); if(sum == finalSum) break; }while(next_permutation(num,num+n)); for(int i = 0;i < n-1;i++) cout << num[i] << " "; cout << num[n-1] << "\n"; } return 0; }
时间: 2024-10-01 19:00:12