硬币找零问题

利用递归算法完成硬币的找零问题,得出找零的最优解

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>change</title>
</head>
<body>
<script>
    function MinCoinChange(coins) {
      var coins=coins;
      var cache={};
      this.makeChange=function (amount) {
        var me=this;
        if(!amount){
          return [];
        }
        if (cache[amount]){
          return cache[amount];
        }
        var min=[],newMin,newAmount;
        for(var i=0;i<coins.length;i++){
          var coin=coins[i];
          newAmount=amount-coin;
          if(newAmount>=0){
            newMin=me.makeChange(newAmount);
          }
          if(newAmount>=0 && (newMin.length<min.length-1 || !min.length)&&(newMin.length || !newAmount)){
            min=[coin].concat(newMin);
            console.log('new Min'+min+'for'+amount);
          }
        }
        return (cache[amount]=min);
      };
    }
    //贪心算法遵循的是一种近似解决问题的技术,期盼通过每个阶段的局部最优选择,从而达到全局的最优
    //最少硬币找零问题
    function MinCoinChange1(coins) {
      var coins=coins;
      this.makeChange=function (amount) {
        var change=[],total=0;
        for(var i=coins.length;i>=0;i--){
          var coin=coins[i];
          while(total+coin<=amount){
            change.push(coin);
            total+=coin;
          }
        }
        return change;
      }
    }
    var minCoinChange=new MinCoinChange([1,3,4]);
    console.log(minCoinChange.makeChange(6));
    var minCoinChange1=new MinCoinChange1([1,5,10,25]);
    console.log(minCoinChange1.makeChange(45));
</script>
</body>
</html>

 

posted @ 2018-07-31 22:16  catchup  阅读(205)  评论(0编辑  收藏  举报