2020秋招华为笔试题-买钉子

1.题目描述

2020秋招华为笔试题-买钉子_第1张图片

2.代码实现

主要思路:类似零钱兑换

#include 
#include 
using namespace std;

class Solution {
public:
    int buyNails(vector& nails, int count) {
        vector dp(count+1, -1);
        dp[0] = 0;

        for(int i = 1; i <= count; i++)
        {
            for(int j = 0; j < nails.size(); j++)
            {
                if(i - nails[j] >= 0 && dp[i-nails[j]] != -1)
                {
                    if(dp[i] == -1 || dp[i] > dp[i-nails[j]]+1)
                        dp[i] = dp[i-nails[j]] + 1;
                }
            }
        }
        return dp[count];
    }
};

int main()
{
    vector nails = {4, 9};
    int n;
    cin >> n;
    Solution s;
    cout << s.buyNails(nails, n) <

 

你可能感兴趣的:(算法)