Backward Digit Sums
FJ and his cows enjoy playing a mental game. They write down the numbers from 1 to N (1 <= N <= 10) in a certain order and then sum adjacent numbers to produce a new list with one fewer number. They repeat this until only a single number is left. For example, one instance of the game (when N=4) might go like this:
3 1 2 4
4 3 6
7 9
16
Behind FJ’s back, the cows have started playing a more difficult game, in which they try to determine the starting sequence from only the final total and the number N. Unfortunately, the game is a bit above FJ’s mental arithmetic capabilities.
Write a program to help FJ play the game and keep up with the cows.
Input
Line 1: Two space-separated integers: N and the final sum.
Output
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.
Sample Input
4 16
Sample Output
3 1 2 4
Hint
Explanation of the sample:
There are other possible sequences, such as 3 2 1 4, but 3 1 2 4 is the lexicographically smallest.
C++编写:
#include<iostream>
#include<cstring>
using namespace std;
int N,sum;
int weights[10],ans[10],used[11];
int solve(int num,int now)
{
if(num==N && now==0) return 1;
if((num==N && now!=0) || now<0) return 0;
for(int i=1;i<=N;i++)
{
if(used[i]==0)
{
ans[num]=i;
used[i]=1;
if(solve(num+1,now-i*weights[num])) return 1;
used[i]=0;
}
}
return 0;
}
int main()
{
ios::sync_with_stdio(false);
cin>>N>>sum;
for(int i=0;i<N;i++) //这个循环其实就是算出杨辉三角的最底层数据
{ //不了解杨辉三角算法可以自己按照该算法一层层画图
weights[i]=1; //有助于理解,确实就这样看是很难懂的
for(int j=i-1;j>0;j--) //这个算法非常之精妙!!!
weights[j] += weights[j-1];
}
memset(used,0,sizeof(used));
solve(0,sum);
for(int j=0;j<N;j++)
{
if(j!=N-1)
cout<<ans[j]<<" ";
else
cout<<ans[j]<<endl;
}
}
这个代码有必要好好地解释一下,首先来看这个计算杨辉三角数据的算法:
for(int i=0;i<N;i++)
{
weights[i]=1;
for(int j=i-1;j>0;j--)
weights[j] += weights[j-1];
}
这里我们假设N=4
当i=0,执行循环第一句,weights[0]=1 ,那么第一行就是weight[0]=1
当i=1,执行循环第一句,weights[1]=1,那么其实第二行就是第一行拿下来右边加个1
当i=2,执行循环第一句,weights[2]=1,此时即是把第二行拿下来右边再加一个1
接着执行第二个for循环,weights[1]=1+1=2,循环结束,那么第三行就是
当i=3,执行循环第一句,weights[3]=1,此时即是把第三行拿下来右边再加一个1
接着执行第二个for循环,weights[2]=1+2=3,weights[1]=2+1=3,循环结束,那么第四行就是
不难发现其实这个算法只要给定N,它就可以计算出第N行的所有数据
再推荐一个别人的代码:https://www.cnblogs.com/fangziyuan/p/5936900.html