2014-12-02 46 views
0

我正在嘗試創建數字列表的所有可能數字組合的子集。下面是一個例子:無法定義循環算法

標記列表:1,2,3,4,5,6

亞羣(3箇中的編號):

1,2,3

1,2,4

1,2,5-

1,2,6

1,3,4

1,3,5-

1,3,6-

1,4,5

1,4,6-

1,5,6

2, 3,4

2,3,5

2,3,6

2,4,5-

2,4,6-

2,5,6-

3,4,5-

3,4,6-

3 ,5,6

4,5,6

我很難試圖確定實現這個列表的循環算法。我可以看到我需要一個嵌套循環,但邏輯逃避我。這個例子包含所有可能的3個數字組,但僅僅是一個例子。我需要能夠擴展到更大的列表和更多的組。請幫忙!

我是一個Java迷,所以我會很感激Java解決方案,但會很滿意任何語言的解釋甚至僞代碼。

+0

做,做的次數事情的順序,或與'5,2,3'相同嗎? – 2014-12-02 16:41:34

+0

歡迎來到stackoverflow!一般來說,嘗試自己開始就會獲得更好的結果,然後如果您遇到問題,請發佈迄今爲止的代碼。這裏的人們通常不想爲人們編寫新的代碼。 – Brian 2014-12-02 16:42:36

+0

幸運的是,Eric Lippert最近寫了一篇關於做這件事的優秀系列! [製作組合(第1部分,共5部分)](http://ericlippert.com/2014/10/13/producing-combinations-part-one/)。他使用C#,但這些想法應該傳遞給Java。 – kaveman 2014-12-02 16:44:34

回答

1

我寫了一個遞歸碼 -

public class SubSetsOfLengthK { 
    public static void main(String[] args) { 
    int n = 6; 
    int k = 3; 

    int[] arr = new int[k]; 
    printSubSets(1,n,k,arr,0); 
} 

/* 
    Method prints all the subsets of length k of set (1.....n) 
*/ 
private static void printSubSets(int start, int n, int k, int[] arr, int pos) { 
    if(k==0) { 
     for(int a : arr) { 
      System.out.print(a+" "); 
     } 
     System.out.println(); 
     return; 
    } 

    for(int j=start;j<= n;j++) { 
     arr[pos] = j; 
     printSubSets(j+1,n,k-1, arr, pos+1); 
    } 
    } 
} 

要快速訪問,你可以在這裏看看,你要排列或組合,即https://coderpad.io/2R9CAG47