1.题目描述:点击打开链接
2.解题思路:本题通过观察发现实际上是找符合这样的等式的一个排列:
C(n-1,0)*a[0]+C(n-1,1)*a[1]+...+C(n-1,n-1)*a[n-1]==sum
其中数组a是1~n的一个排列,C(n-1,i)代表组合数。这样的话,可以花费O(N^2)时间预先计算好所有组合数,然后用next_permutation函数枚举下一个排列即可。如果发现正好等于sum,停止枚举。
3.代码:
#define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<algorithm> #include<string> #include<sstream> #include<set> #include<vector> #include<stack> #include<map> #include<queue> #include<deque> #include<cstdlib> #include<cstdio> #include<cstring> #include<cmath> #include<ctime> #include<functional> using namespace std; #define N 11 int a[N]; int c[N][N]; int n, sum; void init() { for (int i = 1; i < N; i++) c[i][0] = c[i][i] = 1; for (int i = 2; i < N;i++) for (int j = 1; j < i; j++) c[i][j] = c[i - 1][j-1] + c[i - 1][j]; } int main() { //freopen("t.txt", "r", stdin); init(); while (~scanf("%d%d", &n, &sum)) { for (int i = 0; i < n; i++) a[i] = i + 1; do{ int res = 0; for (int i = 0; i < n; i++) res += c[n - 1][i] * a[i]; if (res == sum)break; } while (next_permutation(a , a + n)); for (int i = 0; i < n; i++) printf("%d%c", a[i], i == n - 1 ? '\n' : ' '); } return 0; }
原文地址:http://blog.csdn.net/u014800748/article/details/44940815