-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0416-partition-equal-subset-sum.cs
51 lines (43 loc) · 1.07 KB
/
0416-partition-equal-subset-sum.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
public class Solution
{
public bool CanPartition(int[] nums)
{
var sum = nums.Sum();
if (sum % 2 != 0)
{
return false;
}
return subSetSum(nums, sum / 2);
}
private bool subSetSum(int[] nums, int target)
{
var dp = new bool[nums.Length + 1, target + 1];
for (var i = 0; i < nums.Length + 1; i++)
{
for (var j = 0; j < target + 1; j++)
{
if (i == 0)
{
dp[i, j] = false;
}
if (j == 0)
{
dp[i, j] = true;
}
}
}
for (var i = 1; i < nums.Length + 1; i++)
{
for (var j = 1; j < target + 1; j++)
{
if (nums[i - 1] <= j)
{
dp[i, j] = dp[i - 1, j] || dp[i - 1, j - nums[i - 1]];
}
else
dp[i, j] = dp[i - 1, j];
}
}
return dp[nums.Length, target];
}
}