自然數的拆分


題目鏈接:http://ybt.ssoier.cn:8088/problem_show.php?pid=1318

方法一:DFS

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 int ans[21];      //用於存放答案 
 4 int n, total;    //總方案數
 5 void pr(int d){   //按照要求打印答案 
 6     total+=1;
 7     cout<<n<<"=";
 8     for(int i=1; i<=d-1; i++)cout<<ans[i]<<"+";
 9     cout<<ans[d]<<endl;
10 }
11 void dfs(int dep, int rest){
12     if(rest==0){
13         if(dep>2){   //避免單獨值的出現 
14             pr(dep-1);    
15             return;
16         }
17     }
18     for(int i=ans[dep-1]; i<=rest; i++){
19         ans[dep]=i;
20         dfs(dep+1, rest-i);
21     }
22 }
23 int main()
24 {
25     cin>>n;
26     ans[0]=1;//初始化拆,18行循環語句的初始值 
27     dfs(1, n);
28     //cout<<total;
29     return 0;
30 } 

 方法二:回溯法

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 int ans[21];      //用於存放答案
 4 int n, total;    //總方案數
 5 void pr(int d){   //按照要求打印答案
 6     total+=1;
 7     cout<<n<<"=";
 8     for(int i=1; i<=d-1; i++)cout<<ans[i]<<"+";
 9     cout<<ans[d]<<endl;
10 }
11 void dfs(int dep, int rest){
12     if(rest==0){
13         if(dep>2){   //避免單獨值的出現
14             pr(dep-1);
15             return;
16         }
17     }
18     for(int i=ans[dep-1]; i<=rest; i++){
19         ans[dep]=i;
20         rest=rest-i;
21         dfs(dep+1, rest);
22         rest=rest+i;
23     }
24 }
25 int main()
26 {
27     cin>>n;
28     ans[0]=1;//初始化拆,18行循環語句的初始值
29     dfs(1, n);
30     //cout<<total;
31     return 0;
32 }

 

 回溯法與深度優先搜索的關系


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM