数字组合(未完成)

给定一组数字,求其中任意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); } }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值