跳到主要內容

求出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);
 }
}

留言

這個網誌中的熱門文章

Personal Bookmark

Java SE 6 + Firefox 2 UI 問題 As I do . Google拋棄了了SOAP API,浮想聯翩 https://www.gandi.net/ VS 2005 SP1中文版推出 Windows Vista中文版下載 ASP.NET 2.0網頁執行管線與快取原理 Cache 2.0快取架構與快取資料自動移除架構圖 flickr sync 分享與試用 SUN Looking Glass 3D圖形介面發布1.0 雅虎勵精圖治推動改革 Wait and see 國內某SOC疑遭駭客入侵 大砲開講 Very Important! 微軟公佈Vista安全程式介面草案 一窺Google開原碼庫房乾坤 qing is writing a dig girl net... wait and see

DBeaver 介面語言

DBeaver是我個人頗常用的一套跨平台Database管理工具,最近升級後發現Windows版本居然變成簡體中文,而且無法切換為英文。

自然人憑證讀卡機驅動程式

鳥毅用的是第一代的自然人憑證讀卡機,EZ100PU(後來有同事買EZmini可以讀SIM卡似乎更好),每年報稅時用一次。 本來只是要申請些政府業務,一時之間找不到光碟,沒想到在 驅動程式下載 居然看到Linux和Mac的驅動程式,剩下的就是政府單位的網頁和程式應該改版了吧!!!