获取特定数字的所有组合

时间:2017-03-02 19:36:50

标签: algorithm sorting combinations

这可能是一个简单回答的愚蠢问题,但我无法解决这个问题......:p

因此,如果我有一个变量n = 2,我想要一个列出所有方法的列表,你可以将小于或等于n

的数字组合在一起

n = 2的结果将是:
012
021
102个
120个
201个
210个

感谢您的帮助:)

2 个答案:

答案 0 :(得分:1)

这是一个数学问题,但你试图计算0 - n的排列。

要计算排列,请使用公式nPk,其中,在您的情况下,k是选择的数字n = k + 1。你想取n的阶乘并将其除以n - k的阶乘。 ==> n! / (n - k)!在您的示例中

3!/(3 - 2)! 
3!/1! 
3 * 2 * 1 / 1 = 6 

以下链接详细介绍。 http://www.mathwords.com/p/permutation_formula.htm

答案 1 :(得分:0)

公共类NumberCombination {

public static void combination(int[] num, int x){//x is used to tell from which position in array permutations are needed to be done.
    if(x!=num.length){
        for(int i=x;i<num.length;i++){
            int temp = num[i];
            num[i] = num[x];
            num[x] = temp;
            combination(num,x+1);
            temp = num[i];
            num[i] = num[x];
            num[x] = temp; 
        }
    }
    else{
        for(int i=0;i<num.length;i++)
            System.out.print(num[i]);
        System.out.println();
    }
}

public static void main(String[] args) throws IOException{
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter the number:");
    int n = Integer.parseInt(br.readLine());
    int[] num = new int[n+1];
    for(int i=0;i<=n;i++)
        num[i] = i;
    combination(num, 0);

}

}

相关问题