1. Title Description: Click to open the link
2. How to solve the problem: by observing that the subject is actually looking for an arrangement that conforms to such an equation:
C (n-1,0) *a[0]+c (n-1,1) *a[1]+...+c (n-1,n-1) *a[n-1]==sum
Where array A is an arrangement of 1~n, and C (N-1,i) represents the number of combinations. In this case, you can spend O (n^2) time to pre-calculate all the combinations, and then use the Next_permutation function to enumerate the next permutation. If it finds exactly equal to sum, stop the enumeration.
3. Code:
#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 11int 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_permu Tation (A, A + N)); for (int i = 0; i < n; i++) printf ("%d%c", a[i], i = = n-1? ' \ n ': ');} return 0;}
Backward Digit Sums POJ 3187