想实现一个映射组合算法。但一直没有思路,恳求大佬们给点思路。
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
这种算法有什么思路吗?
1
mario85 2019-04-26 15:16:55 +08:00 2
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 |