一道Java编程题,使用递归来做。

写一个叫做print的类函数,要求如下
public void print(String phrase)
In this method you should use recursive backtracking to find and print all anagrams that can be formed using all of the
letters of the given phrase, in the same order and format as in the example log on the previous page. For example, if your
anagram solver is using the dictionary corresponding to dict1.txt and you are passed the phrase "hairbrush", your
method should produce the following output:
[bar, huh, sir]
[bar, sir, huh]
[briar, hush]
[huh, bar, sir]
[huh, sir, bar]
[hush, briar]
[sir, bar, huh]
[sir, huh, bar]
You should throw an IllegalArgumentException if the string is null. An empty string generates no output.

别介意是全英文的。。具体要求请下载看PDF文档:http://www.cs.washington.edu/education/courses/cse143/12wi/homework/6/spec.pdf
谢谢!

import java.util.*; // in order to use the Set and Stack collections.
public class Anagrams {

private static String[] letters;

/**
* Anagrams, the constructor, initializes a new anagram solver over the given dictionary
* of words, and throws an IllegalArgumentException if the set passed is null.
* @param dictionary
*/
public Anagrams(Set<String> dictionary){
if(dictionary == null)
throw new IllegalArgumentException();
letters = dictionary.toArray(new String[0]);
}

/**
* getWords method returns a set containing all words from the dictionary that can be made
* using some or all of the letters in the given phrase, in alphabetical order, and throws
* an IllegalArgumentException if the set passed is null.
* @param phrase
* @return
*/
public Set<String> getWords(String phrase){
if(phrase == null)
throw new IllegalArgumentException();
Set<String> words = new TreeSet<String>();
LetterInventory phraseLetter = new LetterInventory(phrase);
for(String letter : letters){
if(phraseLetter.contains(letter)){
words.add(letter);
}
}
return words;
}

/**
* This first print method uses recursive backtracking to find and print all
* anagrams that can be formed using all of the letters of the given phrase,
* and throws an IllegalArgumentException if the set passed is null.
* @param phrase
*/
public void print(String phrase){
print(phrase, 0);
}

/**
* This second print method uses recursive backtracking to find and print all anagrams
* that can be formed using all of the letters of the given phrase and that include at
* most max words total, and throws an IllegalArgumentException if the set passed is null.
* @param phrase
* @param max
*/
public void print(String phrase, int max){
if(phrase == null || max < 0)
throw new IllegalArgumentException();
LetterInventory phraseLetter = new LetterInventory(phrase);
Stack<String> chosen = new Stack<String>();
String[] choices = getWords(phrase).toArray(new String[0]);
print(phraseLetter, chosen, choices, max);
}

/**
* This third print method is the basic recursive method of the two print methods above.
* @param phrase, the phrase that the user typed in.
* @param chosen, a collection of the words that are chosen to form the phrase using part
* of letters of the given phrase.
* @param choices, an String array that contains all the possible words that can be used
* to form the given phrase.
* @param max
*/
private static void print(LetterInventory phrase, Stack<String> chosen,String[] choices,int max){
if(phrase.isEmpty()){ //base case
System.out.println(chosen);
}else{ // recursive case
for(int i = 0; i<choices.length;i++){
if(phrase.contains(choices[i]) && (chosen.size() < max || max == 0)){
phrase.subtract(chosen.push(choices[i]));// choose
print(phrase, chosen, choices, max);// explore
phrase.add(chosen.pop());// backtrack.
}
}
}
}
}
温馨提示:内容为网友见解,仅供参考
第1个回答  2016-01-01
public static int triangle(int n) {
if (n == 1) {
return 1;
} else {
return (n + triangle(n - 1));
}
}

程序调用自身的编程技巧称为递归( recursion)。递归做为一种算法在程序设计语言中广泛应用。 一个过程或函数在其定义或说明中有直接或间接调用自身的一种方法,它通常把一个大型复杂的问题层层转化为一个与原问题相似的规模较小的问题来求解,递归策略只需少量的程序就可描述出解题过程所需要的多次重复计算,大大地减少了程序的代码量。递归的能力在于用有限的语句来定义对象的无限集合。一般来说,递归需要有边界条件、递归前进段和递归返回段。当边界条件不满足时,递归前进;当边界条件满足时,递归返回。
第2个回答  2012-05-24
3个字符串进行全排列,用递归算法。下午要考试,不然可以写一写。下面是一个字符串全排列递归算法。你可以看一下。晚上回来写。

public class test{
static int count=0;
public static void main(String[] arg) throws ClassNotFoundException {
String s="1234";
long start=System.currentTimeMillis();
Pailie(s, " ");
System.out.println( "Total: "+count);
long end=System.currentTimeMillis();
System.out.println(end-start);
}
static void Pailie(String s,String p) {
if(s.length() <1) {
count++;
System.out.ptintln(p);
}
else {
int index[]=new int[s.length()];
for(int i=0;i<s.length();i++)
index[i]=s.indexOf(s.charAt(i));
for(int i=0; i <s.length(); i++) {
if(i==index[i])
Pailie(s.substring(1),p+s.substring(0,1));
s=s.substring(1)+s.substring(0,1);
}
}
}
}
第3个回答  2012-05-24
如下

----------------------------------------------------------------------------------------
import java.util.ArrayList;
import java.util.List;

public class demo {

public static void main(String[] args) {
String[] array = { "bar", "huh", "sir" };
List<String> list = new ArrayList();
execute(array, list);
}

public static void execute(String[] array, List<String> list) {
for (int i = 0; i < array.length; i++) {
if (list.contains(array[i])) {
continue;
}
list.add(array[i]);
if (list.size() == array.length) {
String str = "";
for (int n = 0; n < list.size(); n++) {
str += list.get(n) + "\t";
}
System.out.println(str);
} else {
execute(array, list);
}
list.remove(list.size() - 1);
}
}
}
第4个回答  2015-12-23
阶乘用递归实现!!

Java用递归实现3.根据规律写出计算算法:1、7、8、15、23、38、61...
• 因此,第三项是8,第四项是15,第五项是23,以此类推。这是一个典型的递归问题,可以通过递归算法来解决。具体实现代码如下:在上面的代码中,我们定义了一个getNumber方法,该方法接受一个整数n作为参数,返回数列中第n位的值。在该方法中,我们使用了递归算法,把求第n位的值转化为了求...

java编程求1+2+3…+100的和(用递归法)
for(int i=1;i<=100;i++){ sum+=i;} System.out.print(sum);} } 当然你可以将核心代码直接放在main()函数中,也可以放在某个函数中(如sum()),根据你自己的需要进行选择,如果放置在sum()函数中,可以让函数有返回值int,函数体中加return 语句,直接将变量sum返回,这样就不必使用System....

在java中,用递归方法计算n的阶乘。
用Java求键盘输入的数的阶乘n。(递归算法)packagejiecheng; importjava.util.*; \/\/导入java.util包中的所有类classrep{ publiclongrep(intn){ longi=0; if(n==0||n==1) i=1;elsi=n*rep(n-1) returni; } } publicclassJie { publicstaticvoidmain(String[] args) { intn; ...

如何用Java程序编程,最好讲解一下。题目:古典问题:有一对兔子,从出生后...
这道题目考察的是运用递归(数列)的思路去解决问题。假设到第24个月,示例代码如下:public class woo { public static void main(String args[]) { System.out.println(fib(24));} private static int fib(int n) { if (n == 1 || n == 2) { return 1;} else { return fib(n - ...

java用递归编程求斐波那契数列第n项
public static void main(String args[]){ int n,fn;\/\/n为第n项,fn为第n项的值 java.util.Scanner s = new Scanner(System.in);n=s.nextInt();fn=function(n);System.out.println("斐波那契数列第"+n+"项为:"+fn);} public static int function(int n){ if(n==1 || n==2)...

java递归是什么意思?怎么用?通过案例来身临其境的学习java递归
Java递归是一种函数调用自身的技术,用于解决具有重复子问题的问题。它能简化代码,但需谨慎使用以避免潜在的错误和性能问题。接下来,让我们通过实际案例来理解递归的运用。想象每天早晨的洗脸过程:首先打湿脸(washFace()调用wetFace()),然后涂洗面奶(applyCleanser()),再冲洗干净(rinseOff()),...

java递归是什么意思?怎么用?通过案例来身临其境的学习java递归
Java递归是一种技术,用于解决具有重复子问题的问题,其核心是函数调用自身。此方法能让代码简洁明了,但使用不当可能引发程序异常或性能问题。理解递归的关键在于辨认问题中的递归终结条件和递归步骤。下面,我们以简单的“洗脸”为例来解释递归。假设洗脸的步骤可以简化为:打湿、涂洗面奶、冲洗和擦干。将...

java编程计算1+3!+5!+...+(2n-1)! 前10 项和。小弟编写的代码如下
前一位哥们没看清题目 int sum = 0;for (int i = 1; 2*i-1 <= 19; i++) { int sum1 = 1;int x = 2*i-1;for (int j = 1; j <= x; j++) { sum1 = sum1 * j;} sum = sum + sum1;} System.out.println("1~19的奇数阶乘和为"+sum);首先你的循环中i=1在...

用java编写程序输出1,2……n这n个自然数,要求用递归算法
直接调用下面的函数就可以了。displayNum(10);public static void displayNum(int num) { if (num > 1) { displayNum(num - 1);} System.out.println(num);}

在什么情况下可以用递归解决问题?在写递归程序时的原则
1.当某个特性可以被重复执行时,就可以用递归来解决。使用递归某些时候可以减少一些代码量。比如编程题里常见的一道题,求斐波拉切数列:public static int feibolaqie(int num) { if (num < 3)\/\/若num的值为1或2,则返回1 { return 1; } else { return feibolaqie(...

相似回答