Last active
July 1, 2020 15:05
-
-
Save m-khooryani/23e7b129d2c62900b208e603763c5fc8 to your computer and use it in GitHub Desktop.
Partition Problem (DP)
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
This problem was asked by Facebook. | |
Given a multiset of integers, | |
return whether it can be partitioned into two subsets whose sums are the same. | |
For example, given the multiset {15, 5, 20, 10, 35, 15, 10}, | |
it would return true, since we can split it up into {15, 5, 10, 15, 10} and {20, 35}, which both add up to 55. | |
Given the multiset {15, 5, 20, 10, 35}, it would return false, | |
since we can't split it up into two subsets that add up to the same sum. |
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
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
int[] a = new int[] { 15, 5, 20, 10, 35, 15, 10 }; | |
Console.WriteLine(Partition(a, a.Sum() / 2)); // true | |
} | |
private static bool Partition(int[] a, int S) | |
{ | |
bool[,] dp = new bool[a.Length + 1, S + 1]; | |
dp[a.Length, S] = true; | |
for (int i = a.Length - 1; i >= 0; i--) | |
{ | |
for (int j = S; j >= 0; j--) | |
{ | |
dp[i, j] = (j + a[i] <= S && dp[i + 1, j + a[i]]) || dp[i + 1, j]; | |
} | |
} | |
return dp[0, 0]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment