File tree Expand file tree Collapse file tree 1 file changed +28
-0
lines changed Expand file tree Collapse file tree 1 file changed +28
-0
lines changed Original file line number Diff line number Diff line change
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
+ for (int i = 0 ; i < numsSize ; i ++ ) {
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
+ }
You can’t perform that action at this time.
0 commit comments