Skip to content

Instantly share code, notes, and snippets.

@kimhu
Last active August 29, 2015 14:05
Show Gist options
  • Save kimhu/026f3ba4ea855216fd35 to your computer and use it in GitHub Desktop.
Save kimhu/026f3ba4ea855216fd35 to your computer and use it in GitHub Desktop.
implement the sum to the combination of N, the first class has a bug, for example, 6: can not get 2+2+2; the second class works fine.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package testsnmp4j;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
*
* @author kim_hu
*/
public class TestN {
private static Map map = new HashMap();
private static int count = 0;
public static void main(String[] args) {
test(6);
System.out.println(map.keySet().size());
}
public static void test(int m) {
for (int i = 1; i <= m / 2; i++) {
List list = new ArrayList();
for (int j = 0; j < count; j++) {
list.add(1);
}
list.add(i);
list.add(m - i);
map.put(map.keySet().size() + 1, list);
}
count = count + 1;
if (m - 1 > 1) {
test(m - 1);
}
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package testsnmp4j;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
*
* @author kim_hu
*/
public class TestN {
private static Map mapAll = new HashMap();
private static Map mapNeed = new HashMap();
public static void main(String[] args) {
//the sum is 6;
int m = 6;
//the number of the element, for example {2,2,2}
int n = 3;
System.out.println(mapAll.keySet().size());
System.out.println(mapNeed.keySet().size());
}
public static void testN(int num, int n){
List list = new ArrayList();
test(num, 1, num, list);
for(Iterator it = mapAll.keySet().iterator(); it.hasNext();){
List lst = (List) mapAll.get(it.next());
if(lst.size() == n){
mapNeed.put(mapNeed.keySet().size() + 1, lst);
}
}
}
public static void test(int num, int j, int n, List lst) {
List list = new ArrayList(lst);
for (int i = j; i <= n; i++) {
if (i == n && i != num) {
list.add(i);
mapAll.put(mapAll.keySet().size() + 1, list);
list = new ArrayList(lst);
} else if (i != num) {
list.add(i);
test(num, i, n - i, list);
list = new ArrayList(lst);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment