### Adding two recursive methods to new recursion folder.

master
Charles Reid 4 years ago
parent
commit
2 changed files with 145 additions and 0 deletions
1. 72
recursion/threesum/SubsetSum.java
2. 73
recursion/threesum/TripleSum.java

#### 72 recursion/threesum/SubsetSum.java View File

 `@ -0,0 +1,72 @@` `import java.util.*; ` `import java.io.*; ` ``` ``` `/** Find number of subsets of numbers that sum to 0.` ` *` ` * Uses recursive backtracking, and two stacks of integers.` ` *` ` * */` `public class SubsetSum {` ` private static int nsolutions = 0;` ``` ``` ` public static void subsetSums(List list) { ` ` explore(list);` ` }` ``` ``` ` public static int sum(List list) { ` ` int sum = 0;` ` for(int i=0; i superset) { ` ` List brandnew = new ArrayList();` ` System.out.println(explore_(superset, brandnew));` ` }` ``` ``` ` private static int explore_(List unchosen, List chosen) {` ` if(unchosen.isEmpty()) {` ``` // base case ``` ``` // ``` ``` // We may find a combination at any point, so we can never "end early". ``` ``` // We can only keep going until unchosen is empty. ``` ` return nsolutions;` ` } else {` ``` // Check if we have found a sum, in which case, yay! ``` ` if( sum(chosen)==0 ) {` ``` //System.out.println(chosen); ``` ` nsolutions++;` ` }` ``` ``` ``` // recursive case ``` ` for(int j = 0; j < unchosen.size(); j++ ) {` ``` ``` ``` // Make a choice ``` ` Integer element = unchosen.get(j);` ` unchosen.remove(j);` ` chosen.add(element);` ``` ``` ``` // Explore consequences ``` ` explore_(unchosen, chosen);` ``` ``` ``` // Unmake the choice ``` ` chosen.remove(chosen.size()-1);` ` unchosen.add(j,element);` ``` ``` ``` } // move on to next choice ``` ``` ``` ` }` ` return nsolutions;` ` }` ``` ``` ` public static void main(String[] args) { ` ` Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in))); ` ` List list = new ArrayList();` ` while(in.hasNextInt()){` ` list.add(in.nextInt());` ` }` ` subsetSums(list);` ` }` `}`

#### 73 recursion/threesum/TripleSum.java View File

 `@ -0,0 +1,73 @@` ```// Code Jam starting strategy: ``` `import java.util.*;` `import java.io.*;` ``` ``` `public class TripleSum {` ``` ``` ` /** Print all triples ijk such that a[i]+a[j]+a[k] = 0.` ` * Keep it simple:` ` * straightforward approach, simple variable names, ` ` * easy algorithm analysis, printf - only the basics.` ` */` ` public static void printAll(int[] arr) { ` ` int n = arr.length;` ` for(int i=0; i alist = new ArrayList();` ` while(in.hasNextInt()) {` ` alist.add(in.nextInt());` ` }` ``` // turn ArrayList into int[] ``` ` int[] a = new int[alist.size()];` ` for(int i=0; i