整数组合

时间:2012-04-28 18:51:14

标签: java combinations

我对以下问题有任何帮助表示感谢。我有0到n-1的n个整数,并且我试图生成长度为k的所有可能组合的列表(即k个连接的整数),使得每对连续的整数不相等。因此,例如,(1)(2)(3)(2)在k = 4时有效,但(1)(2)(3)(3)无效。关于如何最有效地解决这个问题的任何想法? (我不太关心代码的复杂程度的长度/程度,只关心效率)

3 个答案:

答案 0 :(得分:3)

这是代码:

    void Generate(int[] source, List<int[]> result, int[] build, int k, int num) {
      if (num == k) {
        int[] a = (int[])build.clone();
        result.add(a);
        return;
      }

      for (int i = 0; i < source.length; i++)
        if (num == 0 || source[i] != build[num - 1])
        {
          build[num] = source[i];
          Generate(source, result, build, k, num + 1);
        }
    }

如何致电:

    int k = 2;
    List<int[]> a = new ArrayList<int[]>();
    Generate(new int[]{1,2,3}, a, new int[k], k, 0);

答案 1 :(得分:0)

public static void recursiveOutput(Integer n, int k, int limit, String prints){
    k++;
    if(k>limit)
        return;
    String statePrints = prints;
            //cycle through all available numbers
    for(Integer i = 1; i<=n; i++)
    {
        statePrints = prints;
                    //First cycle
        if(k==1){
            statePrints+= "(" + i.toString() + ")";
            recursiveOutput(n, k, limit, statePrints);
        }
                    //check if predecessor is not the same
        if(i != Integer.parseInt(statePrints.substring(statePrints.length()-2,statePrints.length()-1))){
            statePrints += "(" + i.toString() + ")";
            recursiveOutput(n, k, limit, statePrints);
        }
    }
            //Check if the length matches the combination length
    if(statePrints.length() == 3 * limit)
    System.out.println(statePrints);
}

致电:recursiveOutput(3,0,4,"");

答案 2 :(得分:0)

public class Generator {
    final int k = 2;
    final char[] n = new char[]{'0','1','2','3','4','5','6','7','8','9'};
    final char[] text = new char[k];

    public void gen(int i, int not_n) {
        if(i == k) {
            System.out.println(text);
            return;
        }

        for(int j = 0; j < n.length; j++) {
            if(j == not_n) continue;
            text[i] = n[j];
            gen(i+1, j);
        }

    }
    public static void main(String[] args) {
        new Generator().gen(0, -1);
    }

}