LeetCode 46: Permutations

本文提供了两种不同的排列算法实现:迭代法和递归法。迭代法通过逐层生成新的排列组合来解决问题,而递归法则利用深度优先搜索的方式进行。这两种方法都能有效生成给定数组的所有可能排列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Tips :

1. Need to new array list since it is passed by reference. All the values will be cleaned up the original data is used.

2. For iteraive, no need to copy the last loop result since it should be a new B+ tree layer generation.

Iterative :

 1 public class Solution {
 2     public List<List<Integer>> permute(int[] nums) {
 3         List<List<Integer>> result = new ArrayList<>();
 4         result.add(new ArrayList<>());
 5         
 6         for (int i = 0; i < nums.length; i++) {
 7             List<List<Integer>> newResult = new ArrayList<>();
 8             for (List<Integer> internal : result) {
 9                 for (int j = 0; j <= i; j++) {
10                     List<Integer> newInternal = new ArrayList<>(internal);
11                     newInternal.add(j, nums[i]);
12                     newResult.add(newInternal);
13                 }
14             }
15             result = newResult;
16         }
17         return result;
18     }
19 
20 }

 

 

Recursive : 

 1 public class Solution {
 2     public List<List<Integer>> permute(int[] nums) {
 3         List<List<Integer>> result = new ArrayList<>();
 4         DFS(result, new ArrayList<>(), nums, new boolean[nums.length]);
 5         return result;
 6     }
 7     
 8     private void DFS(List<List<Integer>> result, List<Integer> currentList, int[] nums, boolean[] visited) {
 9         if (currentList.size() == nums.length) {
10             result.add(new ArrayList<>(currentList));
11             return;
12         }
13         
14         for (int i = 0; i < nums.length; i++) {
15             if (visited[i]) {
16                 continue;
17             }
18             visited[i] = true;
19             currentList.add(nums[i]);
20             DFS(result, currentList, nums, visited);
21             currentList.remove(currentList.size() - 1);
22             visited[i] = false;
23         }
24     }
25 }

 

转载于:https://www.cnblogs.com/shuashuashua/p/7223514.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值