print all unique solution to split number n

print all unique solution to split number n, given choice of 1 3 5 10
for example if n is 4
{1, 1, 1, 1}
{1, 3}

思路:用DFS肯定可以求解,但需要遍历所有可能,进行剪纸之后用递推实现。主要剪枝思想,后一个数一定要大于等于前一个数

  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4. vector<vector<int> > res;
  5. vector<int> cur;
  6. void getAllPath(vector<int> &base,int last,int n){
  7. if(n==0) {
  8. res.push_back(cur);
  9. return;
  10. }
  11. for(int i=0;i<base.size();i++) {
  12. if(base[i]>n) return;
  13. if(base[i]<last) continue;
  14. cur.push_back(base[i]);
  15. getAllPath(base,base[i],n-base[i]);
  16. cur.pop_back();
  17. }
  18. }
  19. int main() {
  20. vector<int> base(4);
  21. base[0] = 1;
  22. base[1] = 3;
  23. base[2] = 5;
  24. base[3] = 10;
  25. getAllPath(base,0,8);
  26. for(int i=0;i<res.size();i++) {
  27. for(int j=0;j<res[i].size();j++) {
  28. cout<<res[i][j]<<"\t";
  29. }
  30. cout<<endl;
  31. }
  32. return 0;
  33. }
posted @ 2014-09-10 18:19  purejade  阅读(133)  评论(0编辑  收藏  举报