牛牛凑数字(贪心)

牛牛凑数字(贪心)

思路:贪心。

这个题目挺好的,乍一看选价格最低的使位数最多就完事。

实际需要考虑当有剩余钱时能否与更大的数字进行替换。

比如 1 1 的价格为 2 2 2 2 的价格为 3 3 n = 5 n=5

则最优的答案是: 21 21 ,不是 11 11

因此在找到最大位数后,我们考虑从高位往低位进行替换。

令剩下的钱为: r e s t = n % c n t rest=n\%cnt

r e s t + a [ i d ] a [ j ] rest+a[id]\geq a[j] ,说明可以进行替换,这里我们倒序从数字大到数字小遍历。

直到不满足条件为止。

class Solution {
public:
    string solve(int n, vector<int>& a) {
        int id,cnt=0;
        for(int i=0;i<9;i++) if(cnt<n/a[i]) id=i,cnt=n/a[i];
        if(!cnt) return "-1";
        string ans(cnt,id+'1');
        int rest=n%a[id],k=0;
        for(int j=8;j>0;j--){
            while(rest+a[id]>=a[j]&&k<cnt)
               rest+=a[id]-a[j],ans[k++]=j+'1';
        }
        return ans;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_45750972/article/details/107448815