生活随笔
收集整理的這篇文章主要介紹了
中兴面试题 01背包问题
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
背包問題就是包要滿,但是01背包允許包不滿
?
一,題目:輸入兩個整數(shù) n 和 m,從數(shù)列1,2,3.......n 中隨意取幾個數(shù),使其和等于 m ,要求將其中所有的可能組合列出來。
二,解釋:比如輸入m=4 ?n=4 則輸出為:4
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?1+3 ? 而2+2不正確,因為重復輸出數(shù)字了
? ? ? ? ? ? ? ? ? 中心思想:1)如果1+2+3+……+n<m 則不存在這個數(shù)
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 2)如果m<n 則應該讓n=m //因為m--->n之間的數(shù)都已經(jīng)大于m了 沒必要再計算了
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 3)如果m=n 輸出n
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 4)如果m>n ? 遞歸循環(huá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個數(shù)填滿sum-n????????list1.pop_front();????????find_factor(sum,?n-1);?????//不放n,n-1個數(shù)填滿sum?????}????????int?main()????{????????int?sum,?n;????????cout?<<?"請輸入你要等于多少的數(shù)值sum:"?<<?endl;????????cin?>>?sum;????????cout?<<?"請輸入你要從1.....n數(shù)列中取值的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個數(shù)填滿sum-n list1.pop_front(); find_factor(sum, n-1); //不放n,n-1個數(shù)填滿sum
} int main()
{ int sum, n; cout << "請輸入你要等于多少的數(shù)值sum:" << endl; cin >> sum; cout << "請輸入你要從1.....n數(shù)列中取值的n:" << endl; cin >> n; cout << "所有可能的序列,如下:" << endl; find_factor(sum,n); return 0;
}
總結
以上是生活随笔為你收集整理的中兴面试题 01背包问题的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內容還不錯,歡迎將生活随笔推薦給好友。