POJ - 3187

POJ - 3187

next_permutation 全排列枚举 DFS

题目说的从上到下的加法,特别像杨辉三角,你可以把它斜着来看

这样子加和,最后的答案就在\(b[0]\) 上了

#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
int main() {
    int n,sum,a[10],b[10];
    scanf("%d%d",&n,&sum);
    for(int i = 0;i < n; ++i) a[i] = i + 1;
    while(next_permutation(a,a + n)) {
        int num = 0;
        for(int i = 0;i < n; ++i) b[i] = a[i];
        for(int i = 1;i < n; ++i) {
            for(int j = 0;j < n - i; ++j) {
                b[j] += b[j + 1];
            }
        }
        if(b[0] == sum) break;
    }
    for(int i = 0;i < n; ++i) printf("%d ",a[i]);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/lukelmouse/p/12450064.html
POJ