Partition Equal Subset Sum - #102
Open
Yuto729 wants to merge 1 commit into
Open
Conversation
|
お疲れ様です。 Partition Equal Subset Sumに取り組みました。 問題: https://leetcode.com/problems/partition-equal-subset-sum |
nodchip
reviewed
Aug 9, 2026
| class Solution: | ||
| def canPartition(self, nums: List[int]) -> bool: | ||
| # dp[i][j]: nums[:i + 1]から選んで和がjとなるsubsetを作れる. 0/1ナップザック | ||
| sum_of_nums = sum(nums) |
There was a problem hiding this comment.
こちらのコメントをご参照ください。
h-masder/Arai60#18 (comment)
| return False | ||
|
|
||
| target = sum_of_nums // 2 | ||
| dp = [[False] * (target + 1) for _ in range(len(nums))] |
There was a problem hiding this comment.
dp という変数名は Dynamic Programming の略だと思うのですが、読み手にとってあまり有益な情報になっていないように思います。中にどのような値が含まれるかを端的に表した英単語や英語句を付けると良いと思います。 can_make_sum あたりはいかがでしょうか?
| bits = 1 # 和 0 のみ作れる | ||
| for num in nums: | ||
| bits |= bits << num | ||
| return bits >> target & 1 == 1 |
There was a problem hiding this comment.
演算子の優先順位が分かりにくく感じました。適宜 () で優先順位を明示したほうが、読み手にとって読みやすくなると思います。
return (bits >> target) & 1 == 1|
|
||
| bitset DP | ||
|
|
||
| - 上記一次元DPは[True, False, True, ...]という真偽値の列だが、これを整数1個の各ビットとして表現する |
There was a problem hiding this comment.
この解法は思いつきませんでした。面白い解法だと思います。
Python は int が表現できる範囲に上限が実質ないため、このような書き方ができるのだと思います。また、 CPython では、int は、ある程度の範囲を超えると、多倍長整数として扱われ、桁数に応じた時間計算量と空間計算量がかかる点に注意が必要だと思います。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
解く問題
Partition Equal Subset Sum
次に解く問題