【发布时间】:2017-03-02 19:36:49
【问题描述】:
这可能是一个简单的答案的愚蠢问题,但我一生都无法弄清楚......:p
因此,如果我有一个变量 n = 2,例如,我想要一个列表,列出所有可以组合小于或等于 n 的数字的方法
n = 2 的结果将是:
012
021
102
120
201
210
感谢您的帮助:)
【问题讨论】:
标签: algorithm sorting combinations
这可能是一个简单的答案的愚蠢问题,但我一生都无法弄清楚......:p
因此,如果我有一个变量 n = 2,例如,我想要一个列表,列出所有可以组合小于或等于 n 的数字的方法
n = 2 的结果将是:
012
021
102
120
201
210
感谢您的帮助:)
【问题讨论】:
标签: algorithm sorting combinations
这是一道数学题,但您正在尝试计算 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
【讨论】:
公共类 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);
}
}
【讨论】: