P1025数的划分

P1025数的划分

#include <iostream>

using namespace std;
int n,k;
int cnt;
void dfs(int s,int step,int sum)
//s表示数字,第一个开头的数字,step表示当前记录数字的个数,sum表示数字和
{
    if(step == k){
        if(sum == n) cnt++;
        return;
    }

    for(int i = s; sum + i * (k - step) <= n; i++)
        //i表示当前的数字
        //step表示已经确定的数的个数,k-step表示剩下的数字个数,
        // 如果剩下的数字都是i,还不满足,接下来的搜索也不满足,因此退出
        dfs(i,step+1,sum + i);
}
int main(){
    //freopen("in","r",stdin);
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cin >> n >> k;
    dfs(1,0,0);//表示从1开始计算
    cout << cnt << endl;
}
原文地址:https://www.cnblogs.com/xcfxcf/p/12301605.html