[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;
}