日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

中兴面试题 01背包问题

發布時間:2024/8/1 编程问答 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 中兴面试题 01背包问题 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

背包問題就是包要滿,但是01背包允許包不滿

?

一,題目:輸入兩個整數 n 和 m,從數列1,2,3.......n 中隨意取幾個數,使其和等于 m ,要求將其中所有的可能組合列出來。

二,解釋:比如輸入m=4 ?n=4 則輸出為:4

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?1+3 ? 而2+2不正確,因為重復輸出數字了

? ? ? ? ? ? ? ? ? 中心思想:1)如果1+2+3+……+n<m 則不存在這個數

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 2)如果m<n 則應該讓n=m //因為m--->n之間的數都已經大于m了 沒必要再計算了

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 3)如果m=n 輸出n

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 4)如果m>n ? 遞歸循環

? ? ? ? ? ? ? ? ? 源碼采用原型:0-1背包問題

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?參考博客:http://blog.csdn.net/tianshuai11/article/details/7025464

三,源碼:(類似源碼五)

#include<list>

[html] view plaincopyprint?
  • #include<iostream>????
  • using?namespace?std;????
  • ????
  • list<int>?list1;????
  • void?find_factor(int?sum,?int?n)?????
  • {????
  • ????//?遞歸出口????
  • ????if(n?<=?0?||?sum?<=?0)????
  • ????????return;????
  • ????????
  • ????//?輸出找到的結果????
  • ????if(sum?==?n)????
  • ????{????
  • ????????//?反轉list????
  • ????????list1.reverse();????
  • ????????for(list<int>::iterator?iter?=?list1.begin();?iter?!=?list1.end();?iter++)????
  • ????????????cout?<<?*iter?<<?"?+?";????
  • ????????cout?<<?n?<<?endl;????
  • ????????list1.reverse();????????
  • ????}????
  • ????????
  • ????list1.push_front(n);??????//典型的01背包問題????
  • ????find_factor(sum-n,?n-1);???//放n,n-1個數填滿sum-n????
  • ????list1.pop_front();????
  • ????find_factor(sum,?n-1);?????//不放n,n-1個數填滿sum?????
  • }????
  • ????
  • int?main()????
  • {????
  • ????int?sum,?n;????
  • ????cout?<<?"請輸入你要等于多少的數值sum:"?<<?endl;????
  • ????cin?>>?sum;????
  • ????cout?<<?"請輸入你要從1.....n數列中取值的n:"?<<?endl;????
  • ????cin?>>?n;????
  • ????cout?<<?"所有可能的序列,如下:"?<<?endl;????
  • ????find_factor(sum,n);????
  • ????return?0;????
  • }????
  • #include<iostream> using namespace std; list<int> list1; void find_factor(int sum, int n) { // 遞歸出口 if(n <= 0 || sum <= 0) return; // 輸出找到的結果 if(sum == n) { // 反轉list list1.reverse(); for(list<int>::iterator iter = list1.begin(); iter != list1.end(); iter++) cout << *iter << " + "; cout << n << endl; list1.reverse(); } list1.push_front(n); //典型的01背包問題 find_factor(sum-n, n-1); //放n,n-1個數填滿sum-n list1.pop_front(); find_factor(sum, n-1); //不放n,n-1個數填滿sum } int main() { int sum, n; cout << "請輸入你要等于多少的數值sum:" << endl; cin >> sum; cout << "請輸入你要從1.....n數列中取值的n:" << endl; cin >> n; cout << "所有可能的序列,如下:" << endl; find_factor(sum,n); return 0; }


    總結

    以上是生活随笔為你收集整理的中兴面试题 01背包问题的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。