我的Java实现:
package com.herosoft.algorithm;
import java.io.*;
class Combination {
private int count;
private int[] s;
public Combination(int n, int r) {
if (n < r) {
int temp;
temp = n;
n = r;
r = temp;
}
s = new int[n];
count = count(n, r);
System.out.println("there are total:count: " + count);
for (int i = 0; i < r; i++) {
s[i] = i + 1;
System.out.printf("%2d", s[i]);
}
System.out.println();
permutation(n, r);
}
void permutation(int n, int r) {
for (int i = 1; i < count; i++) {
int m = r - 1, max_value = n;
// notice: good logic
while (s[m] == max_value) {
m = m - 1;
max_value = max_value - 1;
}
// if (s[m] + 1 == s[0])
// s[m] = s[m] + 1;
s[m] = s[m] + 1;
for (int j = m + 1; j < r; j++) {
s[j] = s[j - 1] + 1;
}
for (int k = 0; k < r; k++) {
System.out.printf("%2d", s[k]);
}
System.out.println();
}
}
// compute value of c(n,r)
static int count(int n, int r) {
int sn = 1, sr = 1, s_r = 1;
for (int i = 1; i <= n; i++) {
sn *= i;
}
for (int j = 1; j <= r; j++) {
sr *= j;
}
for (int k = 1; k <= n - r; k++) {
s_r *= k;
}
sr *= s_r;
return sn / sr;
// combination logic: only return sn/s_r, not to need sr
// return sn/s_r;
}
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("please input n :");
int n = Integer.parseInt(in.readLine());
System.out.println("please input r :");
int r = Integer.parseInt(in.readLine());
new Combination(n, r);
}
}
以下摘自求组合数问题!http://topic.csdn.net/t/20050808/09/4194872.html
[@more@]1.递归...#include
using namespace std;
int m,n,*p;
void main()
{
cin>>m>>n;
p=new int[n+1];
for(int i=0;i
p[i]=i+1;
}
p[n]=m+1;
while(p[0]!=m-n+1)
{
for(i=0;i
cout<}
cout<
while(p[k]==m-n+k+1)
{
k--;
}
p[k]++;
for(int a=k+1;a
p[a]=p[a-1]+1;
}
}
for(i=0;i
cout<
cout<
http://topic.csdn.net/t/20050808/09/4194872.html
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/220284/viewspace-1028102/ ,如需转载,请注明出处,否则将追究法律责任。