zoukankan      html  css  js  c++  java
  • 01背包问题的非递归解

    0-1背包问题:求:从1,2,3,。。。n中取若干个数,使和为m,输出所有序列的非递归算法,其中,m>n

    void print(vector<int> &v){  
    for(vector<int>::iterator it=v.begin();it!=v.end();it++){
    cout
    <<*it<<" ";
    }
    cout
    <<endl;
    }
    void algorithm(int m,int n){
    vector
    <int> p;//记录Path
    int i=n;
    int j=n;
    int temp_m=m;
    p.reserve(
    10);
    while(i*(1+i)/2>=m){
    p.clear();
    j
    =i;
    temp_m
    =m;
    while(true){
    if(j==0)
    break;
    if(temp_m-j>0){
    p.push_back(j);
    temp_m
    -=j;
    j
    --;
    }
    else if(temp_m-j<0){
    j
    --;
    }
    else{
    p.push_back(j);
    print(p);
    if(p.size()>0&&p[p.size()-1]!=1){
    p.pop_back();
    j
    --;
    continue;
    }
    else{
    break;
    }
    }
    }
    i
    --;
    }
    }
    int main(){
    algorithm(
    10,7);
    }

    
    
  • 相关阅读:
    列表 ,表格与媒体元素基础
    HTML5基础知识
    解析
    字符串
    类和对象
    [leetcode]605. Can Place Flowers能放花吗
    [leetcode]432. All O`one Data Structure全O(1)数据结构
    [leetcode]68. Text Justification文字对齐
    [leetcode]149. Max Points on a Line多点共线
    [leetcode]272. Closest Binary Search Tree Value II二叉搜索树中最近的值II
  • 原文地址:https://www.cnblogs.com/CUCmehp/p/1314148.html
Copyright © 2011-2022 走看看