星期六, 4月 07, 2012

求出n取k組合的列表 Java 版

求出n取k組合的列表 CSharp版中是用CSharp寫,用Java則幾乎相同,只是Java的ArrayList可以是Container,指定型別看起來爽一點。



以下為Java版code:

Combinations.java

import java.util.ArrayList;

public class Combinations
{
 private ArrayList <String> list;
 
 public ArrayList<String> Calc(int all, int want)
 {
  list = new ArrayList<String>();
  char [] fake = new char[0];
  Calc(fake, all, want);
  System.out.println("Total: "+list.size()+" combinations." );
  for(String str : list)
  {
   System.out.println(str);
  }
  return list;
 }

 void AddList (String before, String after)
 {
  list.add(before+ after);
 }
 
 protected void Calc(char[] before, int all, int want)
 {
  char []strAll = new char[all];
  if(want == 0)
  {
   for(int i=0; i<all;i++)
   {
    strAll[i] = '0';
   }
   AddList (new String(before),  new String(strAll));
  }
  else if(all == want) {
   for(int i=0; i<all;i++)
   {
    strAll[i] = '1';
   }
   AddList (new String(before),  new String(strAll));
  }
  else if(all == 1)
  {
   switch(want)
   {
   case 0:
    AddList(new String(before),  "0");
    break;
   case 1:
    AddList(new String(before),  "1");
    break;
   }
  }
  else // all must > want
  {
   char [] newbefore = new char[before.length +1];
   for(int i=0; i< before.length; i++)
   {
    newbefore[i] = before[i];
   }
   newbefore[before.length]='0';
   Calc (newbefore, all-1, want);
   newbefore[before.length]='1';
   Calc (newbefore, all-1, want-1);
  }
 }
 
 public static void main (String[] args)
 {
  Combinations cn = new Combinations();
  cn.Calc(5, 2);
 }
}

沒有留言: