यह एक क्लासिक Dynamic Programming समस्या (भी अन्य उत्तर 0-1 बस्ता और सबसेट योग समस्याओं के साथ इसकी समानता का उल्लेख द्वारा इंगित) की तरह दिखता है।पूरी चीज एक साधारण पसंद तक उबालती है: सूची में प्रत्येक तत्व के लिए, क्या हम इसे अपने योग में उपयोग करते हैं या नहीं। के बाद से इस समारोह अतिव्यापी subproblems (यह एक ही subproblems बार बार की पड़ताल), यह एक अच्छा विचार के साथ समारोह memoize है है
f(index,target_sum)=
0 if target_sum<=0 (i.e. we don't need to add anymore)
infinity if target_sum>0 and index is past the length of n (i.e. we have run out of numbers to add)
min(f(index+1,target_sum), f(index+1,target_sum-n[index])+n[index]) otherwise (i.e. we explore two choices - 1. take the current number 2. skip over the current number and take their minimum)
: हम जवाब गणना करने के लिए एक सरल पुनरावर्ती क्रिया ऊपर लिख सकते हैं पहले से गणना की गई मानों को पकड़ने के लिए एक कैश।
यहाँ अजगर में कोड है:
#! /usr/bin/env python
INF=10**9 # a large enough number of your choice
def min_sum(numbers,index,M, cache):
if M<=0: # we have reached or gone past our target, no need to add any more
return 0
elif len(numbers)==index: # we have run out of numbers, solution not possible
return INF
elif (index,M) in cache: # have been here before, just return the value we found earlier
return cache[(index,M)]
else:
answer=min(
min_sum(numbers,index+1,M,cache), # skip over this value
min_sum(numbers,index+1,M-numbers[index],cache)+numbers[index] # use this value
)
cache[(index,M)]=answer # store the answer so we can reuse it if needed
return answer
if __name__=='__main__':
data=[10,6,3,100]
M=11
print min_sum(data,0,M,{})
यह समाधान केवल न्यूनतम राशि, न कि वास्तविक इसे बनाने के लिए इस्तेमाल किया तत्वों देता है। आप आसानी से अपने समाधान में जोड़ने के विचार को बढ़ा सकते हैं।
सबसे अच्छा उदाहरण मैं सोच सकता हूं कि एम मान के शॉपिंग वाउचर को देखते हुए, मैं एक स्टोर में जाता हूं और उत्पादों का चयन करता हूं जैसे कि मैं वाउचर का पूर्ण उपयोग करूँगा और शेष राशि को ऊपर उठाने के लिए न्यूनतम नकदी का भुगतान करूंगा। यदि मैं 1 से अधिक संयोजन उत्पन्न करता हूं जो समान कुल मूल्य उत्पन्न करता है तो मैं कम से कम उत्पादों के साथ संयोजन का चयन भी करूंगा। –
चुनने के लिए उत्पादों की कम से कम राशि योग होगी {n [?] + N [c] + ...} जहां sum> एम। क्या मैं गलत हूं? – Chris
इसकी राशि> = एम, प्राथमिकता सेट पर जा रही है जहां योग और एम के बीच का अंतर कम से कम है। यदि दो सेटों का एक ही योग है, तो कम से कम 'उत्पादों' के साथ सेट –