The minimum number of coins the sum of which is S

后端 未结 12 1357
我寻月下人不归
我寻月下人不归 2020-11-30 05:06

Given a list of N coins, their values (V1, V2, ... , VN), and the total sum S. Find the minimum number of coins the sum of which is S (we can use as many coins of one type a

12条回答
  •  日久生厌
    2020-11-30 05:32

    int getMinCoins(int arr[],int sum,int index){
    
            int INFINITY=1000000;
            if(sum==0) return 0;
            else if(sum!=0 && index<0) return INFINITY;
    
            if(arr[index]>sum) return getMinCoins(arr, sum, index-1);
    
            return Math.min(getMinCoins(arr, sum, index-1), getMinCoins(arr, sum-arr[index], index-1)+1);
        }
    

    Consider i-th coin. Either it will be included or not. If it is included, then the value sum is decreased by the coin value and the number of used coins increases by 1. If it is not included, then we need to explore the remaining coins similarly. We take the minimum of two cases.

提交回复
热议问题