[depth-first search] division of integers

Do k-step selection. Since it cannot be repeated, the selected number must not decrease monotonically, and the range of the number that can be selected at each step is the number of the previous step~n

dfs(index,sum,choice): The choice of index-1 has been done, and the sum is sum, the choice of the previous step is choice

if(sum>n)return;

if(index==k+1){

  if(sum==n){res++};return;}

 

#include<iostream>
using namespace std;
int n;
int k;
int res=0;
void dfs(int index,int sum,int choice){
	if(sum>n)return;
	if(index==k+1){
	  if(sum==n){
	  	res++;
	  }
	  return; 
	}
	for(int i=choice;i<=n;i++)
	dfs(index+1,sum+i,i); 
}
int main(){
	cin>>n>>k;
	dfs(1,0,1);
	cout<<res;
}

Guess you like

Origin blog.csdn.net/m0_52043808/article/details/123943279