Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 6eda77c

Browse files
ADD Partition-Equal-Subset-Sum problem #66
1 parent f37a805 commit 6eda77c

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

‎Medium/partition-equal-subset-sum.cs

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
5+
public class Solution
6+
{
7+
private static bool _IsOdd(int num) => (num % 2 != 0);
8+
9+
private static bool _IsThereSubsetContainsTheTarget(int[] nums, int target)
10+
{
11+
if (nums == null || nums.Length == 0)
12+
{
13+
return false;
14+
}
15+
16+
HashSet<int> dp = new HashSet<int>();
17+
dp.Add(0);
18+
19+
for (int i = nums.Length - 1; i >= 0; i--)
20+
{
21+
HashSet<int> nextDP = new HashSet<int>();
22+
foreach (int t in dp)
23+
{
24+
if (t + nums[i] == target)
25+
{
26+
return true;
27+
}
28+
29+
nextDP.Add(t + nums[i]);
30+
nextDP.Add(t);
31+
}
32+
33+
dp = nextDP;
34+
}
35+
36+
return dp.Max() == target;
37+
}
38+
39+
public static bool CanPartition(int[] nums)
40+
{
41+
if (nums == null || nums.Length == 0)
42+
{
43+
return false;
44+
}
45+
46+
int totalAll = nums.Sum();
47+
48+
if (_IsOdd(totalAll))
49+
{
50+
return false;
51+
}
52+
53+
if (nums.Length == 2)
54+
{
55+
return (nums[0] == nums[1]);
56+
}
57+
58+
return _IsThereSubsetContainsTheTarget(nums, totalAll / 2);
59+
}
60+
61+
public static void Main(string[] args)
62+
{
63+
int[] nums = { 1, 2, 3, 4, 5, 6, 7 };
64+
65+
Console.WriteLine(CanPartition(nums));
66+
67+
Console.ReadKey();
68+
}
69+
}
70+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /