高手指点(有难度)

天空win 2011-01-17 03:55:39
从键盘输入两个自然数N,R(N>R),要求输入从N到1中按降序顺序取R个自然数的

所有组合个数。
输入:N=5,R=3
输出:543,542,541,532,531,521,432,431,421,321
Total=10
...全文
230 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
dracularking 2011-01-18
  • 打赏
  • 举报
回复

public class Test {
public static void main(String args[]) {
new Test().go(5, 3);
}

public void go(int startnumber, int length) {
for(int i = startnumber; i >= length; i--) {
generate("", i, length);
}
}

public void generate(String prenumber, int startnumber, int length) {
if(length == 2) {
for(int i = startnumber - 1; i > 0; i--) {
System.out.println(prenumber + startnumber + "" + i);
}
} else {
for(int i = startnumber - 1; i >= length - 1; i--) {
generate(prenumber + String.valueOf(startnumber), i, length - 1);
}
}
}
}

递归的话定义一个嵌套讯混
generate(5, 3) = 5 + generate(4, 2)
5 + generate(3, 2)
5 + generate(2, 2)
而generate(startnumber, length)
在这里的概念是生成以startnumber为起始的length个数的所有序列
天空win 2011-01-18
  • 打赏
  • 举报
回复
当时想到肯定要用递归。但是没做出来!

谢谢!递归用的特别好。
茫茫大海 2011-01-17
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 keeya0416 的回复:]
Java code

public class Test {

public static int total = 0;

public static void main(String[] args) {
method(5,3);
}

public static void method(int n, int r)……
[/Quote]
支持这位兄弟,递归用的非常好啊!学习了!
liumingchang 2011-01-17
  • 打赏
  • 举报
回复
LZ 发帖3个,结帖0个
deadgod 2011-01-17
  • 打赏
  • 举报
回复
inner(i - 1, index + 1, arr);
用的很强大!
茫茫大海 2011-01-17
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 keeya0416 的回复:]
Java code

public class Test {

public static int total = 0;

public static void main(String[] args) {
method(5,3);
}

public static void method(int n, int r)……
[/Quote]
用递归很好,就不知道楼主能看懂不!
keeya0416 2011-01-17
  • 打赏
  • 举报
回复

public class Test {

public static int total = 0;

public static void main(String[] args) {
method(5,3);
}

public static void method(int n, int r){
if(n <= r) return;
inner(n, 0, new int[r]);
System.out.println("Total: " + total);
}

private static void inner(int num, int index, int[] arr){
if(index == arr.length){
for (int i = 0; i < arr.length; i++) {
System.out.printf("%d ", arr[i]);
}
System.out.println();
total++;
}else{
for (int i = num; i >= arr.length - index; i--) {
arr[index] = i;
inner(i - 1, index + 1, arr);
}
}
}
}
kevindude 2011-01-17
  • 打赏
  • 举报
回复
本来还想贴答案的,一看到结贴率为0。。。

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧