zoukankan      html  css  js  c++  java
  • 递归实现数字拆分

     1 #include<iostream>
     2 #include<string>
     3 #include<algorithm>
     4 #include<vector>
     5 #include<cmath>
     6 #include<set>
     7 using namespace std;
     8 
     9 void splitnum(int n, int k, int &way, vector<int> ans) //对n进行拆分,拆分数的最小值为k
    10 {
    11     if((n>=k && n<2*k) || n==0)
    12     {
    13         way++;
    14         if(n!=0)
    15             ans.push_back(n);
    16 
    17         cout<<"way "<<way<<":"<<endl;
    18         for(unsigned j=0; j<ans.size(); j++)
    19             cout<<ans[j]<<" ";
    20         cout<<endl;
    21 
    22         return;
    23     }
    24 
    25     for(int i=k; i<=n; i++)
    26     {
    27         ans.push_back(i);
    28 
    29         if(n-i>=i || n-i==0)
    30             splitnum(n-i, i, way, ans);
    31 
    32         ans.pop_back();
    33 
    34     }
    35 }
    36 
    37 int main()
    38 {
    39     int T,n;    
    40     cin>>T;
    41 
    42     for(int i=0; i<T; i++)
    43     {
    44         cin>>n;
    45         int way=0;
    46         splitnum(n, 1, way, vector<int>());
    47         cout<<way<<endl;
    48     }
    49 
    50     return 0;
    51 }

    代码中包含了拆分的结果显示部分,题目中只需输出拆分种类数即可,对于给出的三个测试样例结果正确,其他结果有待验证,并且用递归实现非常耗时,提交后出现TLE。

    运行结果:

     

  • 相关阅读:
    密码学
    MD5
    计算机基础之操作系统
    python中列表之间求差集、交集、并集
    Python语言中各种进制相互转换
    计算机基础
    bzoj2705 [SDOI2012]Longge的问题
    bzoj3160 万径人踪灭
    codeforces 528D Fuzzy Search
    杜教筛 && bzoj3944 Sum
  • 原文地址:https://www.cnblogs.com/Marrybe/p/3825618.html
Copyright © 2011-2022 走看看