簡體   English   中英

Min Coin Change - 動態規划

[英]Min Coin Change - Dynamic Programming

問題 - 您將獲得不同面額的硬幣和總金額。 編寫一個函數來計算組成該數量所需的最少硬幣數量。硬幣的供應量是無限的。

我的方法 - 我遵循自上而下的方法,但使用 map stl 進行記憶,我得到了 TLE。 請幫助找出錯誤並估計時間復雜度。

這是我的代碼 -

// for example coins v = {1,2} and W = 2 then possible solutions are -
// (2) or (1, 1), therefore minimum number of coins required is 1.
// Below is the function calculating the minimum number of coins required for change

int minCoinChange(vector<int> &v, int start, int W, unordered_map<string, int> &lookup){

// v denoting the vector conataining coins with given denomination
// start denoting the start index i.e. 0(initially)
// W denoting the required change
// lookup is map stl for storing values.

// base cases 
    if(W<0){
        return INT_MAX;
    }
    if(W == 0){
        return 0;
    }
    if(start >= v.size()){
        return INT_MAX;
    }

// for memoization creating the "key"
    string key = to_string(start) + '|' + to_string(W);

// if the key is not found in map then go inside if 
    if(lookup.find(key) == lookup.end()){
        int excl = minCoinChange(v, start+1, W, lookup); // if element is excluded

        int incl = 1 + minCoinChange(v, start, W - v[start], lookup); if element is included 

        lookup[key] = min(incl, excl); // calculating minimum number of coins required and storing in map 
    }
// if key is already there then return value stored in map 
    return lookup[key]; 
}

首先, unordered_map的最壞情況是O(n)查找時間。 有一些方法可以優化unordered_map性能,例如使用map.reserve(n)保留桶的數量,其中n是您希望在地圖中擁有的唯一項目的數量。

您可以改用map ,它的最壞情況為O(log(n))查找時間,但由於該算法的時間復雜度為O(n * W)您的nW將足夠小以適合數組,然后你將有O(1)查找。

下面是修改您的函數以使用數組查找:

int minCoinChange(vector<int> &v, int start, int W, vector<vector<int>> &lookup){

    // v denoting the vector conataining coins with given denomination
    // start denoting the start index i.e. 0(initially)
    // W denoting the required change
    // lookup is 2d vector for storing already computed values.

    // base cases 
    if (W<0) {
        return 1e9;
    }
    if (W == 0) {
        return 0;
    }
    if (start >= v.size()) {
        return 1e9;
    }

    // if this state wasn't computed before
    if (lookup[start][W] == -1) {
        int excl = minCoinChange(v, start+1, W, lookup); // if element is excluded

        int incl = 1 + minCoinChange(v, start, W - v[start], lookup); // if element is included 

        lookup[start][W] = min(incl, excl); // calculating minimum number of coins required and storing in map 
    }
    // return the saved value
    return lookup[start][W];
}

筆記:

對於基本情況,不要使用INT_MAX ,如果向它添加1就會溢出,而是使用10^9類的東西。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM