java全排列算法怎么实现

40次阅读
没有评论

共计 903 个字符,预计需要花费 3 分钟才能阅读完成。

以下是一种实现 Java 全排列算法的方法:

import java.util.ArrayList;
import java.util.List;
public class Permutation {public static void main(String[] args) {int[] nums = {1, 2, 3};
List<List> permutations = permute(nums);
System.out.println(permutations);
}
public static List<List> permute(int[] nums) {List<List> result = new ArrayList();
backtrack(result, new ArrayList(), nums);
return result;
}
private static void backtrack(List<List> result, List tempList, int[] nums) {if (tempList.size() == nums.length) {result.add(new ArrayList(tempList));
} else {for (int i = 0; i < nums.length; i++) {if (tempList.contains(nums[i])) {continue; // 跳过已经添加过的数字}
tempList.add(nums[i]);
backtrack(result, tempList, nums); // 递归调用
tempList.remove(tempList.size() - 1); // 回溯
}
}
}
}

在这个实现中,我们使用了回溯算法来生成全排列。我们定义了一个 backtrack 方法来生成所有可能的排列。在每一步中,我们将一个数字添加到临时的排列中,在递归调用后,我们将该数字从临时排列中移除,以便进行下一次尝试。当临时排列的长度等于输入数组的长度时,我们将其添加到结果列表中。
上述代码的输出结果为 [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]],即为输入数组[1, 2, 3] 的所有全排列。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-20发表,共计903字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)