[C++]Backward Digit Sums
Backward Digit Sums:
给出一行数(从1到N),按杨辉三角的形式叠加到最后,可以得到一个数,现在反过来问你,如果我给你这个数,你找出一开始的序列(可能存在多个序列,输出字典序最小的那个)。
输入格式:
Line 1: Two space-separated integers: N and the final sum.
输出格式:
Line 1: An ordering of the integers 1…N that leads to the given sum. If there are multiple solutions, choose the one that is lexicographically least, i.e., that puts smaller numbers first.
输入:
4 16
输出:
3 1 2 4
解题思路: 数组1~n,用全排列反向计算,当杨辉三角的值最后相加为目标值时,输出数组序列。
AC代码:
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int n, sum;
int mp[13];
int main(){
cin>>n>>sum;
for(int i = 1; i<=n; i++){
mp[i] = i;
}
do{
int b[13];
for(int i=1;i<=n;i++)
b[i]=mp[i];
for(int i=n; i>=2; i--)
{
for(int j=1; j<i; j++)
{
b[j]=b[j]+b[j+1];
}
}
if(b[1] == sum){
break;
}
}while(next_permutation(mp, mp+n+1));
for(int i = 1; i<=n; i++){
cout<<mp[i]<<" ";
}
return 0;
}