Skip to content

Partition Equal Subset Sum - #102

Open
Yuto729 wants to merge 1 commit into
mainfrom
partition-equal-subset-sum
Open

Partition Equal Subset Sum#102
Yuto729 wants to merge 1 commit into
mainfrom
partition-equal-subset-sum

Conversation

@Yuto729

@Yuto729 Yuto729 commented Aug 9, 2026

Copy link
Copy Markdown
Owner

解く問題

Partition Equal Subset Sum

次に解く問題

@github-actions

github-actions Bot commented Aug 9, 2026

Copy link
Copy Markdown

お疲れ様です。

Partition Equal Subset Sumに取り組みました。
お手隙の際にレビューをお願いいたします。

問題: https://leetcode.com/problems/partition-equal-subset-sum
PR: #102
言語: Python3

class Solution:
def canPartition(self, nums: List[int]) -> bool:
# dp[i][j]: nums[:i + 1]から選んで和がjとなるsubsetを作れる. 0/1ナップザック
sum_of_nums = sum(nums)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

こちらのコメントをご参照ください。
h-masder/Arai60#18 (comment)

return False

target = sum_of_nums // 2
dp = [[False] * (target + 1) for _ in range(len(nums))]

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

dp という変数名は Dynamic Programming の略だと思うのですが、読み手にとってあまり有益な情報になっていないように思います。中にどのような値が含まれるかを端的に表した英単語や英語句を付けると良いと思います。 can_make_sum あたりはいかがでしょうか?

bits = 1 # 和 0 のみ作れる
for num in nums:
bits |= bits << num
return bits >> target & 1 == 1

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

演算子の優先順位が分かりにくく感じました。適宜 () で優先順位を明示したほうが、読み手にとって読みやすくなると思います。

return (bits >> target) & 1 == 1


bitset DP

- 上記一次元DPは[True, False, True, ...]という真偽値の列だが、これを整数1個の各ビットとして表現する

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

この解法は思いつきませんでした。面白い解法だと思います。

Python は int が表現できる範囲に上限が実質ないため、このような書き方ができるのだと思います。また、 CPython では、int は、ある程度の範囲を超えると、多倍長整数として扱われ、桁数に応じた時間計算量と空間計算量がかかる点に注意が必要だと思います。

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.

2 participants