Created
June 1, 2017 19:13
-
-
Save jianminchen/e34e91029f9b85971c66fddfca41d586 to your computer and use it in GitHub Desktop.
Leetcode 39 - combination sum - past all test cases
This file contains 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
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace Leetcode39_CombinationSum | |
{ | |
class Leetcode39_CombinationSum | |
{ | |
/* | |
* understand the design issue: | |
* the bug to avoid: | |
Input: | |
[2,3,6,7] | |
7 | |
Output: | |
[[2,2,3],[2,3,2],[3,2,2],[7]] | |
Expected: | |
[[2,2,3],[7]] | |
*/ | |
static void Main(string[] args) | |
{ | |
} | |
public IList<IList<int>> CombinationSum(int[] numbers, int target) | |
{ | |
var subsets = new List<IList<int>>(); | |
var subset = new List<int>(); | |
findSubsetWithSum(subsets, subset, numbers, target, 0); | |
return subsets; | |
} | |
/// <summary> | |
/// using recursive function to conduct depth first search | |
/// </summary> | |
/// <param name="allSubsets"></param> | |
/// <param name="subset"></param> | |
/// <param name="numbers"></param> | |
/// <param name="remaining"></param> | |
/// <param name="start"></param> | |
private void findSubsetWithSum( | |
IList<IList<int>> allSubsets, | |
IList<int> subset, | |
int[] numbers, | |
int remaining, | |
int start) | |
{ | |
// boundary check - sum value | |
if(remaining < 0) | |
{ | |
return; | |
} | |
// base case | |
if(remaining == 0) | |
{ | |
allSubsets.Add(subset); | |
return; | |
} | |
// depth first search using recusive function | |
for (int i = start; i < numbers.Length; i++) | |
{ | |
var visit = numbers[i]; | |
var current = i; | |
var newList = new List<int>(subset); | |
newList.Add(visit); | |
findSubsetWithSum(allSubsets, newList, numbers, remaining - visit, current); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment