假设我有一个班级:
class Content {
public String contentid;
public String locationid;
public Content(String n, String l) {
contentid = n;
locationid = l;
}
}
现在我们有3个位置,分别是locationid 1,2,3。位置1有3个内容,有争议的2,3,4,位置2有3个内容,有争议的1,2,3,位置3有2个内容,有争议的1,2。现在我想找到这3个区域的所有内容的所有组合,每个区域只能选择1个内容。
这是我使用dfs(递归)的解决方案。
public static List<List<Content>> dfs(String digits, Map<String, List<Content>> m) {
List<List<Content>> result = new ArrayList<List<Content>>();
if(digits.length() == 0){
return new ArrayList<List<Content>>();
}
if(digits.length() == 1){
return new ArrayList<>(Arrays.asList(m.get(Character.toString(digits.charAt(0)))));
}
List<List<Content>> intermediate = dfs(digits.substring(1, digits.length()),m);
for(Content first : m.get(Character.toString(digits.charAt(0)))){
for(List<Content> rest : intermediate){
rest.add(first);
result.add(rest);
}
}
return result;
}
主要:
// key is locationid, and values are list of contents
Map<String, List<Content>> m= new HashMap<>();
m.put("1", Arrays.asList("2","3","4"));
m.put("2", Arrays.asList("1","2","3"));
m.put("3", Arrays.asList("1","2"));
List<List<Content>> result=dfs("123",m);
System.out.print(result.size());
然而,我的输出是9这是错误的,它应该是3x3x2 = 18。我已经调试了一个小时,无法找到问题所在。