We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 47f9ae2 commit 85f317aCopy full SHA for 85f317a
c/0416-partition-equal-subset-sum.c
@@ -0,0 +1,28 @@
1
+bool canPartition(int* nums, int numsSize) {
2
+ int totalSum = 0;
3
+ for (int i = 0; i < numsSize; i++) {
4
+ totalSum += nums[i];
5
+ }
6
+
7
+ if (totalSum % 2 != 0) {
8
+ return false; // If the total sum is odd, we cannot partition equally
9
10
11
+ int targetSum = totalSum / 2;
12
+ bool dp[targetSum + 1]; // dp[i] represents whether a subset with sum i is possible
13
14
+ // Initialize dp array
15
+ for (int i = 0; i <= targetSum; i++) {
16
+ dp[i] = false;
17
18
+ dp[0] = true; // Empty subset can always achieve sum 0
19
20
+ // Dynamic programming approach
21
22
+ for (int j = targetSum; j >= nums[i]; j--) {
23
+ dp[j] = dp[j] || dp[j - nums[i]];
24
25
26
27
+ return dp[targetSum];
28
+}
0 commit comments