湊零錢算法,給出一整數,用給定的面值的錢,拼湊成該整數

題目:給你 k 種面值的錢,面值分別爲 c1, c2 ... ck,再給一個總金額 n,問你最少需要多少張錢湊出這個金額,如果不可能湊出,則回答 -1 。

比如說,k = 3,面值分別爲 1,2,5,總金額 n = 11,那麼最少需要 3 枚張,即 11 = 5 + 5 + 1 。下面走流程。

思路:將k中面值,分別放入List集合中,並進行從大到小的排序,假設集合名字爲coinList判斷最大面值的錢是否比總金額n大。大於則將最大面值從集合總移除,第二大的面值的錢,作爲集合中第一個元素。若小於n,則用n除以面值List集合集合中的第一個元素。得到一個int temp=n/coinList.get(0) 整數,將該面值coinList.get(0)和數量temp存到對象中,並存結果List集合。然後用n=n-(temp*coinList.get(0)),移除coinList.remove(0),然後按照此步驟循環下去。直到n=0;

實現代碼如下

import java.util.List;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import lombok.Data;

public class ChangeMin {
	public static void main(String[] args){
		int n=106;
	    List<Integer> coinList=new ArrayList<Integer>();
	    List<Change> resList=new ArrayList<Change>();
	    coinList.add(1);
	    coinList.add(100);
	    coinList.add(5);
	    coinList.add(10);
	    coinList.add(20);
	    coinList.add(50);
	    List<Change> changeByList = getChangeByList(n,coinList,resList);
	    List<Integer> tableNames=changeByList.stream().map(Change::getAmount).collect(Collectors.toList());
	    int totalValue = changeByList.stream().mapToInt(Change::getAmount).sum();
	    JSONArray jsonArray = (JSONArray) JSONArray.toJSON(changeByList);
	    JSONObject jsonObject = new JSONObject();
	    LinkedHashMap<String, Object> linked = new LinkedHashMap<String,Object>();
	    linked.put("count", totalValue);
	    linked.put("result", jsonArray);
	    String jsonString = JSON.toJSONString(linked);
	    System.out.println(jsonString);
	}
	
	
	/**
	 * 湊零錢算法,給出指定的金額,用指定面額的紙幣,用最少張數湊足零錢
	 * @param n
	 * @param coinList
	 * @return
	 */
	public static List<Change> getChangeByList(int n,List<Integer> coinList,List<Change> resList){
		Collections.sort(coinList,Collections.reverseOrder());
		if(n>0){
			Change change = new Change();
			if(coinList.size()>0){
			Integer max = coinList.get(0);
			int temp=0,result=0;
			List<Integer> tempList=new ArrayList<Integer>();
			if(n<max){
				coinList.remove(0);
				result=n;
			}else{
				temp=n/max;
	            result=n-(temp*max);
	            change.setChange(max);
	            change.setAmount(temp);
	            resList.add(change);
			}
			getChangeByList(result,coinList,resList);
			}
		}
		return resList;

	}  

}
@Data
class Change{
	private int change;
	private int amount;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章