我正在编写一个程序来列出字符串的所有子集。我的程序(如下所示)按以下顺序列出了“abcd”的子集:
'' 'd' 'c' 'cd' 'b' 'bd' 'bc' 'bcd' 'a' 'ad' 'ac' 'acd' 'ab' 'abd' 'abc' 'abcd'
哪个是对的。但是,参考解决方案按以下顺序列出它们:
'' 'a' 'b' 'ab' 'c' 'ac' 'bc' 'abc' 'd' 'ad' 'bd' 'abd' 'cd' 'acd' 'bcd' 'abcd'
我的问题是:这个订单的名称是什么?
作为参考,这是我的程序:
import java.util.ArrayList;
import java.util.Collections;
/**
This class generates subsets of a string.
*/
public class SubsetGenerator
{
public static ArrayList<String> getSubsets(String word)
{
ArrayList<String> result = new ArrayList<String>();
//fill out
//result.add("");
if(word.length() == 0)
{
result.add("");
}
else
{
String notFirst = word.substring(1);
ArrayList<String> smaller = getSubsets(notFirst);
//System.out.println(smaller);
char first = word.charAt(0);
result.addAll(smaller);
for(String i: smaller)
{
result.add(first+i);
}
}
//simpleSubsets = getSubsets(simple+word.charAt(0));
// Form a simpler word by removing the first character
// fill out
// Generate all subsets of the simpler word
// fill out
// Add the removed character to the front of
// each subset of the simpler word, and
// also include the word without the removed character
// fill out
// Return all subsets
return result;
}
}