现在我的程序输出[m,r,rm,ru,rum,u,um],由于某种原因递归方法不输出rm答案。我一直跟踪它,但我似乎无法正确追踪它并找到问题所在。我不确定丢失的子集在哪里?谢谢!
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
Prints subsets of String
*/
public class SubsetGenerator
{
private String word="";
private ArrayList<String> subsets;
/**
Constructs a word to generate subsets from
@param text input by user
*/
public SubsetGenerator(String textinput)
{
word=textinput;
subsets = new ArrayList<String>();
}
/**
retrieves word
@return the word
*/
public String getWord()
{
return word;
}
/**
get subsets
@return subset arraylist
*/
public ArrayList<String> getSubsets()
{
if(word.length()==0)
{
subsets.add("");
return subsets;
}
else
{
String removed=word.substring(0,1);
word=word.substring(1);
subsets.add(removed);
for(int i=0;i<word.length();i++)
{
String temp=removed+word.substring(0,i+1);
subsets.add(temp);
}
}
getSubsets();
return subsets;
}
}
/**
This program tests the subset generator.
*/
public class SubsetGeneratorTester
{
public static void main(String[] args)
{
SubsetGenerator generator = new SubsetGenerator("rum");
List<String> subsets = generator.getSubsets();
// Sort the result for checking
Collections.sort(subsets);
System.out.println(subsets);
System.out.println("Expected: [, m, r, rm, ru, rum, u, um]");
}
}
答案 0 :(得分:0)
如果你想抓住word.substring()
,你还需要沿着rm
的起点进行迭代。
public ArrayList<String> getSubsets()
{
if(word.length()==0)
{
subsets.add("");
return subsets;
}
else
{
String removed=word.substring(0,1);
word=word.substring(1);
subsets.add(removed);
for(int i=0;i<word.length();i++)
{
for(int j=0; j<=i; j++){
String temp=removed+word.substring(j,i+1);
subsets.add(temp);
}
}
}
getSubsets();
return subsets;
}
}