Title Address
Brief test Instructions:
Enter two numbers n and M, respectively, to give you 1--n these integers, put them in a certain order in a row, according to the Yang Hui triangle calculation method to sum, so that they find that the final result is equal to m in the arrangement of the smallest dictionary order.
Thinking Analysis:
It is not difficult to push the first action n the number of A1\a2\......\an and for the i=0∑n-1 ai* (N-1CI) According to this formula, considering the data volume is small, only need to be in ascending order of 1--n according to Next_ The permutation gives the increment in the full order, one by one, if the result is equal to M to stop the loop.
Reference code:
1#include <stdio.h>2#include <cstring>3#include <iostream>4#include <algorithm>5 using namespacestd;6typedefLong Longll;7 intfact[ One],ncr[ One][ One],b[Ten]={1,2,3,4,5,6,7,8,9,Ten};//get the 1--n ready first.8 intMain ()9 {Ten inti,j; Onefact[0]=fact[1]=1;//due to the small data, first preprocessing, calculate the factorial A for(i=2; i<=Ten; i++) - { -fact[i]=fact[i-1]*i; the } - for(i=1; i<=Ten; i++) - { - for(j=0; j<=i/2; j + +) + { -Ncr[i][j]=ncr[i][i-j]= (fact[i]/(fact[j]*fact[i-j));//calculate each combination number + } A } at intN,he,de; -scanf"%d%d",&n,&He); -n--; - if(n==0) -printf"1\n"); - Else{ inDe=0; - for(i=0; i<=n;i++)//first determine whether the initial increment of the situation is satisfied, after the call next_permutation seems to be directly from the second item began to { +de+=b[i]*Ncr[n][i]; - } the if(de==He) * { $ for(i=0; i<=n;i++)Panax Notoginseng { -printf"%d", B[i]); the } + return 0; A } the while(Next_permutation (b,b+n+1))//Full arrangement + { -De=0; $ for(i=0; i<=n;i++) $ { -de+=b[i]*Ncr[n][i]; - } the if(de==He) - {Wuyi for(i=0; i<=n;i++) the { -printf"%d", B[i]); Wu } - Break; About } $ } -printf"\ n"); - } - return 0; A}
(DFS, full array) POJ-3187 backward Digit Sums