C++ 求解一整数划分问题

未命名要

 

 

 

// rec.cpp : 定义控制台应用程序的入口点。
#include "stdafx.h"
#include <iostream>
#include <sstream>
#include <list>
#include <vector>
#include <string>
#include <stdexcept>
using namespace std;
//把数字转换为字符串
string convertstrtoint(int j){
  stringstream tempstream;
  tempstream<<j;
  string i;
  tempstream>>i;
  tempstream.clear();
  tempstream.str("");
  return i;
}
//递归求解。。。
string recsmallt(int n,string result,int curtotal, int total)
{
    string temp="";
  if(curtotal==total)  return result+",";
    for(int j=n;j>0;j--){
       if(curtotal+j==total)
         {           
           temp=temp+ result+"+"+convertstrtoint(j)+",";
       
         }
      if(curtotal+j<total){
             temp=temp+recsmallt(j,result+"+"+convertstrtoint(j),curtotal+j,total); 
        }
    }
  return temp;
}
void getres(int n)
{
  string finalresult="";
  for(int j=n;j>0;j--){
     //去掉最后面的逗号
       finalresult=recsmallt(j,convertstrtoint(j),j,n);
     finalresult.resize(finalresult.size()-1);
     cout<<finalresult<<endl;
  }
}
int _tmain(int argc, _TCHAR* argv[])
{
  
    getres(6);
  system("pause");
    return 0;
}

 

 

另外一种算法:

#include <Windows.h>
#include <stdio.h>
#include <vector>
using namespace std;
void print(unsigned int x)
{
  vector<int> vec;
  unsigned int count;
  vec.push_back(x);
  count = x;
  unsigned int pos = vec.size() - 1;
  while(vec[0] != 0){
    if(vec[pos] == 0){
      //进行回溯
      vec.pop_back();
      pos--;
      vec[pos] --;
      count --;
    }else if(count < x){
      //后面数均不大于前面的数
      vec.push_back(vec[pos]);
      pos++;
      count += vec[pos];
    }else if(count > x){
      //后面的不能比前面的大,由于缺少判断,这里进行返回操作
      count--;
      vec[pos] --;
    }else if(count == x){
      //满足要求,打印,下一轮初始化
      for(int i = 0; i <= pos; i++)
        printf("%d ", vec[i]);
      printf("\n");
      vec[pos]--;
      count --;
    }
  }
  return;
  
}
int main(int argc, char**argv)
{
  print(9);
  return 0;
}
posted @ 2012-04-30 12:49  ForFreeDom  阅读(1625)  评论(0编辑  收藏  举报