LeetCode 322. Coin Change

本文讨论了使用不同面额的硬币凑齐指定金额的最少数量,并提供了求解此类问题的算法。还涉及了硬币组合的总数、交换次数到总金额的计算方法。同时,通过实例演示了如何解决这些问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


General DP question.

#include <vector>
#include <iostream>
#include <climits>
using namespace std;

/*
  You are given coins of different denominations and a total amount of money amount.
  write a function to compute the fewest number of coins that you need to make up
  the amount. If that amount of money cannot be made up by any combination of the coins.
  return -1.
  Example:
  coins = [1, 2, 5], amount = 11
  return 3 (11 == 5 + 5 + 1)
  coins = [2], amount = 3;
  return -1;
*/

int coinChange(vector<int>& coins, int amount) {
  vector<int> dp(amount+1, INT_MAX);  // this initialize is very important. since some value can't be exchanged.
  dp[0] = 0;
  for(int i = 1; i <= amount; ++i) {
    for(int j = 0; j < coins.size(); ++j) {
      if(i - coins[j] >= 0) {
        int sub_res = dp[i-coins[j]];
        if(sub_res != INT_MAX && sub_res + 1 < dp[i]) dp[i] = sub_res + 1;
      }
    }
  }
  if(dp[amount] == INT_MAX) return -1;
  return dp[amount];
}

int main(void) {
  vector<int> coins{2, 5};
  cout << coinChange(coins, 8) << endl;
  cout << coinChange(coins, 3) << endl;
}

// Variations.
// Get the total number of coin exchanges to the whole sum.
// number of ways combinations.
// table[i][j] == table[i][j] + table[i][j-coins[k]];
int coinCombinations(int sum, vector<int>& coins) {
  int n = coins.size();
  vector< vector<int> > table(sum + 1, vector<int>(n, 0));
  for(int i = 0; i < n; ++i) {
    table[0][i] = 1;
  }
  for(int i = 1; i <= sum; ++i) {
    for(int j = 0; j < n; ++j) {
      int x = (i - coins[j] >= 0) ? table[i - coins[j]][j] : 0;
      int y = (j >= 1) ? table[i][j-1] : 0;
      table[i][j] = x + y;
    }
  }
  return table[sum][n - 1];
}

// To further optimize,
 int exchange(vector<int>& coins, int sum) {
  vector<int> dp(sum + 1, 0);
  dp[0] = 1;
  int n = coins.size();
  for(int i = 0; i < n; ++i) {
    for(int j = coins[i]; j <= sum; ++j) {
      dp[j] += dp[j - coins[i]];
    }
  }
  return dp[sum];
}

Another variation:

Given a non-negative number n, find out how many ways n can be made by summing up non-negative integers.

int waysSum(int n) { // these are all backpacking series problems.
  vector< vector<int> > dp(n + 1, vector<int>(n + 1, 0));
  for(int j = 0; j < n; ++j) {
    dp[0][j] = 1;
  }

  for(int i = 0; i <= n; ++i) {
    for(int j = 1; j <= n; ++j) {
      // do not include j.
      dp[i][j] = dp[i][j-1];
      if(i - j >= 0) {
        dp[i][j] += dp[i-j][j];
      }
    }
  }
  return dp[n][n];
}

int main(void) {
  cout << waysSum(2) << endl;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值