|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Linq; |
| 4 | +using Newtonsoft.Json; |
| 5 | +using NUnit.Framework; |
| 6 | + |
| 7 | +[TestFixture] |
| 8 | +public class TestClass : TestClassBase |
| 9 | +{ |
| 10 | + [TestCase("[1,2,3]", 3)] |
| 11 | + [TestCase("[10,7,4,10,8,4,2,3,9,9]", 55)] |
| 12 | + public void TestMethod1(string candidatesString, int target) |
| 13 | + { |
| 14 | + var candidates = JsonConvert.DeserializeObject<int[]>(candidatesString); |
| 15 | + var expectedResult = CombinationSum2(candidates, target); |
| 16 | + var result = new Solution().CombinationSum2(candidates, target); |
| 17 | + Assert.AreEqual(Serialize(expectedResult), Serialize(result), string.Format("{0}. {1}.", candidatesString, target)); |
| 18 | + } |
| 19 | + |
| 20 | + [TestCase(10, 10, 100)] |
| 21 | + public void TestMethod2(int maxLength, int maxValue, int repeatTimes) |
| 22 | + { |
| 23 | + Repeat(repeatTimes, () => |
| 24 | + { |
| 25 | + var candidates = GenerateIntegerArray(0, maxLength, 1, maxValue); |
| 26 | + var candidatesString = JsonConvert.SerializeObject(candidates); |
| 27 | + var target = Random.Next(1, Math.Max(2, candidates.Sum() + 2)); |
| 28 | + TestMethod1(candidatesString, target); |
| 29 | + }); |
| 30 | + } |
| 31 | + |
| 32 | + private IList<IList<int>> CombinationSum2(int[] candidates, int target) |
| 33 | + { |
| 34 | + var results = new List<IList<int>>(); |
| 35 | + Search(results, new Stack<int>(), candidates, target, 0); |
| 36 | + results = results.GroupBy(item => JsonConvert.SerializeObject(item)).Select(g => g.First()).ToList(); |
| 37 | + return results; |
| 38 | + } |
| 39 | + |
| 40 | + private void Search(IList<IList<int>> results, Stack<int> temp, int[] candidates, int remaining, int index) |
| 41 | + { |
| 42 | + if (remaining == 0) |
| 43 | + { |
| 44 | + if (temp.Count > 0) |
| 45 | + { |
| 46 | + results.Add(temp.OrderBy(x => x).ToList()); |
| 47 | + } |
| 48 | + return; |
| 49 | + } |
| 50 | + if (remaining < 0 || index >= candidates.Length) |
| 51 | + { |
| 52 | + return; |
| 53 | + } |
| 54 | + temp.Push(candidates[index]); |
| 55 | + Search(results, temp, candidates, remaining - candidates[index], index + 1); |
| 56 | + temp.Pop(); |
| 57 | + Search(results, temp, candidates, remaining, index + 1); |
| 58 | + } |
| 59 | + |
| 60 | + private string Serialize(IList<IList<int>> results) |
| 61 | + { |
| 62 | + return JsonConvert.SerializeObject(results.OrderBy(item => JsonConvert.SerializeObject(item)).Select(item => item)); |
| 63 | + } |
| 64 | +} |
0 commit comments