例如,如果元素是{1, 2} (n = 2)和m = 3,则该方法应生成这样的数组列表{[1,1,1],[1,1,2],[1,2,1],[2,1,1],[1,2,2],[2,2,1],[2,1,2],[2,2,2]}.
我知道Python可以做类似的事情y = itertools.product((1, 2), repeat=3),但我如何有效地在Java中实现它.我已尝试提供一些初始List并使用以下内容来获得我想要的但时间复杂度太高而且当输入很大时性能非常糟糕.
public static List<List<Integer>> permute (List<Integer> list, int need) {
List<List<Integer>> result = new ArrayList<>();
if (need--==0) {
result.add(list);
return result;
}
for (int current : list)
insert(permute(list,need), current, result);
return result;
}
private static void insert(List<List<Integer>> currentLists, int currentInt, List<List<Integer>> list) {
for (List<Integer> currentList : currentLists) {
int size = currentList.size();
for (int i = 0; i <= size; …Run Code Online (Sandbox Code Playgroud) java ×1