Skip to content

Conversation

@potrue
Copy link
Owner

@potrue potrue commented Aug 8, 2025

public:
int coinChange(vector<int>& coins, int amount) {
vector<int> viable_coins;
for (const int coin : coins) {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

範囲 for 文でプリミティブ型変数で回すときは、 const は付けないことが多いように思います。好みの問題かもしれません。

vector<int> fewest_coins(amount + 1, -1);
fewest_coins[0] = 0;
for (int i = 0; i < amount; ++i) {
if (fewest_coins[i] != -1) {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

真偽を反転して continue し、ネストを下げたほうが読みやすくなると思います。

if (fewest_coins[i] != -1) {
for (const int coin : viable_coins) {
if (i + coin <= amount) {
if (fewest_coins[i + coin] == -1) {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fewest_coins を -1 ではなく大きな数字で初期化すると、 if 文が消せ、

fewest_coins[i + coin] = min(fewest_coins[i + coin], fewest_coins[i] + 1);

だけで済むようになり、シンプルになると思います。

int coinChange(vector<int>& coins, int amount) {
vector<int> min_coins(amount + 1, -1);
min_coins[0] = 0;
for (int i = 0; i <= amount; ++i) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i よりは合計金額という意味がわかる変数名だとわかりやすいと思いました。

Copy link
Owner Author

@potrue potrue Aug 9, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

本当はamountという変数名をつけたかったんですが、もともとの関数の引数の名前に取られてたのでiにしました。
ただ今考えたら勝手に変数名変えても別にleetcodeの実行上は支障なかったですね。
おっしゃる通りこちらのほうがわかりやすいと思います!

class Solution {
public:
    int coinChange(vector<int>& coins, int target_amount) {
        vector<int> min_coins(target_amount + 1, -1);
        min_coins[0] = 0;
        for (int amount = 0; amount <= target_amount; ++amount) {
            if (min_coins[amount] == -1) continue;
            for (const int coin : coins) {
                if (coin > target_amount - amount) continue;
                min_coins[amount + coin] = min_coins[amount + coin] == -1
                                        ? min_coins[amount] + 1
                                        : min(min_coins[amount + coin], min_coins[amount] + 1);
            }
        }
        return min_coins.back();
    }
};

class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
vector<int> min_coins(amount + 1, -1);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

枚数としてあり得ない大きい数で初期化したい派です。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants