给定一组数字,求其中任意K个数的组合并将各种组合存储返回
来自一道1100分的topcoder习题,该死的递归快把人搞死了,从网上查到了解决方案但还是理解的不很透彻,最大问题是返回的String值不能对原数据进行区分,尝试用ArrayList也不行,现在脑子一团糟,在博客上记录一下,以后有更好的方法再过来改
如果路过的高手有什么好的建议,敬请指教
public class Polygons2 { static ArrayList co_term = new ArrayList(); static int count = 0; public static void number(int[] segmention, int K) { long result = 0; int N = segmention.length; //cacu the number of ways of combination int co_n = 1; for (int i = N; i > K; i--) { co_n *= i; } String temp = ""; combin(segmention, K, temp, 0); String[] combin_result = (String[]) co_term.toArray(new String[co_term.size()]); // combin_result=combin_result.substring(1,co_term.size()-1); for (String com : combin_result) { System.out.println(com); } } public static void combin(int[] original, int k, String temp, int start) { if (k == 0) { co_term.add(temp); //co_term.add(","); } else { for (int i = start; i < original.length; i++) { temp += (String.valueOf(original[i])); //co_term.add(" "); combin(original, k - 1, temp, i + 1); //co_term.remove(temp.substring(temp.length())); temp = temp.substring(0, temp.length() - 1); } } } // public static void combin(int[] original, int k, int start) { // ArrayList temp = new ArrayList(); // if (k == 0) { // co_term.add(temp); // co_term.add(","); // } else { // for (int i = start; i < original.length; i++) { // temp.add(original[i]); // co_term.add(String.valueOf(original[i]) + " "); // combin(original, k - 1, temp, i + 1); // temp.remove(temp.size()); // //co_term.remove(co_term.size()-1); // } // } // } public static void main(String[] args) { int[] segmention = {10, 1, 4, 9, 20}; int K = 4; number(segmention, K); } }