diff --git a/README.md b/README.md index 109cd1ab..d464d84b 100644 --- a/README.md +++ b/README.md @@ -37,6 +37,8 @@ This directory contains various types of algorithm questions like Dynamic Progra 2. [Math](algorithms/math) 3. [Sorting](algorithms/sorting) 4. [Greedy](algorithms/greedy) +5. [Graph](algorithms/graph) +6. [Backtracking](algorithms/backtracking) 5. [Misc](algorithms/miscellaneous) ### Bookmarks diff --git a/algorithms/backtracking/combination_sum.py b/algorithms/backtracking/combination_sum.py new file mode 100644 index 00000000..e536945b --- /dev/null +++ b/algorithms/backtracking/combination_sum.py @@ -0,0 +1,30 @@ +""" +High Level Description: +Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), +find all unique combinations in candidates where the candidate numbers sums to target. +The same repeated number may be chosen from candidates unlimited number of times. + +Note: +* All numbers (including target) will be positive integers. +* The solution set must not contain duplicate combinations. +""" + +def combinationSum(candidates, target): + res = [] + candidates.sort() + dfs(candidates, target, 0, [], res) + return res + +def dfs(nums, target, index, path, res): + if target < 0: + return # backtracking + if target == 0: + res.append(path) + return + for i in range(index, len(nums)): + dfs(nums, target-nums[i], i, path+[nums[i]], res) + +'''Usage Example''' +# candidates = [2,3,6,7] +# target = 7 +# print(combinationSum(candidates, target)) \ No newline at end of file diff --git a/algorithms/backtracking/combinations.py b/algorithms/backtracking/combinations.py new file mode 100644 index 00000000..1ad9ab04 --- /dev/null +++ b/algorithms/backtracking/combinations.py @@ -0,0 +1,15 @@ +""" +High Level Description: +Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. + +Time Complexity: +O(2^n) +""" + +def combine(n, k): + if k == 0: + return [[]] + return [pre + [i] for i in range(k, n+1) for pre in combine(i-1, k-1)] + +'''Usage Example''' +# print(combine(5,3)) \ No newline at end of file diff --git a/algorithms/backtracking/subset.py b/algorithms/backtracking/subset.py new file mode 100644 index 00000000..232eea60 --- /dev/null +++ b/algorithms/backtracking/subset.py @@ -0,0 +1,21 @@ +""" +High Level Description: +Given a set of distinct integers, S, return all possible subsets. + +Time Complexity: +O(2^n) +""" + +def subsets(nums): + res = [] + dfs(sorted(nums), 0, [], res) + return res + +def dfs(nums, start, path, res): + res.append(path) + for i in range(start, len(nums)): + dfs(nums, i+1, path+[nums[i]], res) + +'''Usage Example''' +# S = [1, 2, 3] +# print(subsets(S)) \ No newline at end of file