请教大佬们一个算法问题

2019-04-25 23:16:10 +08:00
 akabe2134

想实现一个映射组合算法。但一直没有思路,恳求大佬们给点思路。

int[] input={1, 2, 3,3};

// k=是上面的索引,v=是索引对应的值
Map<Integer, List<String>> g = new HashMap<>();
g.put(1, Lists.newArrayList("a"));
g.put(2, Lists.newArrayList("b"));
g.put(3, Lists.newArrayList("c", "d"));

       

最终组合出的结果应该是:

a,b,c,c

a,b,c,d

a,b,d,c

a,b,d,d

这种算法有什么思路吗?

691 次点击
所在节点    问与答
1 条回复
mario85
2019-04-26 15:16:55 +08:00
import java.util.*;

public class MyClass {
public static List<String> 映射组合算法(int[] input, Map<Integer, List<String>> g, int layer, List<String> inters)
{
List<String> nodes = g.get(input[layer]);
List<String> result;
if(inters == null)
result = nodes;
else {
result = new ArrayList();
for(String inter : inters)
for(String node : nodes)
result.add(inter + node);
}

layer++;
if(layer >= input.length)
return result;
else
return 映射组合算法(input, g, layer, result);
}

public static void main(String args[]) {
int[] input={1, 2, 3,3};

// k=是上面的索引,v=是索引对应的值
Map<Integer, List<String>> g = new HashMap<>();
g.put(1, Arrays.asList("a"));
g.put(2, Arrays.asList("b"));
g.put(3, Arrays.asList("c", "d"));

List<String> result = 映射组合算法(input, g, 0, null);
for(String s:result)
System.out.println(s);
}
}

Result...
CPU Time: 0.16 sec(s), Memory: 29456 kilobyte(s)compiled and executed in 0.899 sec(s)
abcc
abcd
abdc
abdd

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/558787

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX