Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Find the count of subsets with given difference
//Microsoft (R) Visual C# Compiler version 3.4.0-beta4-19562-05 (ff930dec) //Copyright (C) Microsoft Corporation. All rights reserved. using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace Rextester { public class Program { public static void Main(string[] args) { int[] arr = new int[] { 1, 1, 2, 3}; int diff = 1; //Formula or trick to find the count of subsets with given difference // s1 - s2 = diff // s1 - (sum - s1) = diff // s1 - sum + s1 = diff // 2s1 - sum = diff // 2s1 = diff + sum // s1 = (diff + sum) / 2; int s1 = (diff + arr.Sum()) / 2; Console.WriteLine(CountSubsetSum (arr, s1) + " subsets found with given difference " + diff); } private static int CountSubsetSum (int[] arr, int sum) { int[,] t = new int[arr.Length+1, sum+1]; for (int i=0; i < t.GetLength(0); i++) { for (int j=0; j < t.GetLength(1); j++) { if (j == 0) { t[i, j] = 1; continue; } if (i == 0) { t[i, j] = 0; continue; } if (arr[i-1] <= j) { t[i, j] = t[i-1, j - arr[i-1]] + t[i-1, j]; } else { t[i, j] = t[i-1, j]; } } } return t[arr.Length, sum]; } } }
run
|
edit
|
history
|
help
0
Escape's Vanity Fair (Malformed \p {X} character escape)
Download a UTF-8 text file, and display the contents.
Bubble Sort
Swiss Infotech Tutorial
Convert from one encoding to another
Is String a Palindrome
actions and tasks
asxasxasd
Convert string to int
LINQ