Ai
1 Star 0 Fork 0

geekplayers/Leetcode-1-300

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
_46_Permutations.java 2.90 KB
一键复制 编辑 原始数据 按行查看 历史
Cspiration 提交于 2019-01-31 06:49 +08:00 . Add files via upload
package leetcode_1To300;
import java.util.ArrayList;
import java.util.List;
/**
* 本代码来自 Cspiration,由 @Cspiration 提供
* 题目来源:http://leetcode.com
* - Cspiration 致力于在 CS 领域内帮助中国人找到工作,让更多海外国人受益
* - 现有课程:Leetcode Java 版本视频讲解(1-900题)(上)(中)(下)三部
* - 算法基础知识(上)(下)两部;题型技巧讲解(上)(下)两部
* - 节省刷题时间,效率提高2-3倍,初学者轻松一天10题,入门者轻松一天20题
* - 讲师:Edward Shi
* - 官方网站:https://cspiration.com
* - 版权所有,转发请注明出处
*/
public class _46_Permutations {
/**
* Given a collection of distinct numbers, return all possible permutations.
For example,
[1,2,3] have the following permutations:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
time : O(n!)
space : O(n);
reference : http://www.1point3acres.com/bbs/thread-117602-1-1.html
The number of recursive calls, T(n) satisfies the recurrence T(n) = T(n - 1) + T(n - 2) + ... + T(1) + T(0),
which solves to T(n) = O(2^n). Since we spend O(n) time within a call, the time complexity is O(n2^n);
* @param nums
* @return
*/
// time : O(n! * n) space : O(n);
public static List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
if (nums == null || nums.length == 0) return res;
helper(res, new ArrayList<>(), nums);
return res;
}
public static void helper(List<List<Integer>> res, List<Integer> list, int[] nums) {
if (list.size() == nums.length) {
res.add(new ArrayList<>(list));
return;
}
for (int i = 0; i < nums.length; i++) {
if (list.contains(nums[i])) continue; // O(n)
list.add(nums[i]);
helper(res, list, nums);
list.remove(list.size() - 1);
}
}
// time : O(n!) space : O(n);
public static List<List<Integer>> permute2(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
if (nums == null || nums.length == 0) return res;
helper2(res, 0, nums);
return res;
}
public static void helper2(List<List<Integer>> res, int start, int[] nums) {
if (start == nums.length) {
List<Integer> list = new ArrayList<>();
for (int num : nums) {
list.add(num);
}
res.add(new ArrayList<>(list));
return;
}
for (int i = start; i < nums.length; i++) {
swap(nums, start, i);
helper2(res, start + 1, nums);
swap(nums, start, i);
}
}
public static void swap(int[] nums, int l, int r) {
int temp = nums[l];
nums[l] = nums[r];
nums[r] = temp;
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/geekplayers/Leetcode-1-300.git
git@gitee.com:geekplayers/Leetcode-1-300.git
geekplayers
Leetcode-1-300
Leetcode-1-300
master

搜索帮助