Leetcode Permutation

本文深入探讨了如何使用深度优先搜索(DFS)算法解决字符串全排列问题,通过树形结构展示递归过程,详细解释了从输入字符串到输出所有可能组合的实现细节。

Problem

Give a string, like “abc”, return all the possible combinations (all the chars are different)

example:
input: “abc”
output: [abc, acb, bac, bca, cab, cba]

Analysis

obviously, this problem can be solved by dfs. We should know that all the dfs problem can be shown as a tree form. So once we transfer the problem into a tree, the problem is solved.

             " "
      /       |      \
   a          b        c
   | \        | \      | \
  ab  ac      ba bc    ca cb
  |   |       |  |     |   |
 abc acb    bac bca   cab cba

Coding

// An highlighted block
class Solution1 {
	public static List<String> mutation(String str){
		
		List<String> res = new LinkedList<String>();
		
		String temp = "";
		dfs(str, res, temp, str.length());
		
		
		return res;
	}
	
	public static void dfs(String str, List<String> res, String temp, int len ) {
		
		// base case
		if (temp.length() == len) {
			res.add(temp);
			return;
		}
		
		// recursive rule
		for (int i=0; i<str.length(); i++) {
			if (temp.indexOf(str.charAt(i)) < 0) {
				dfs(str, res, temp + str.charAt(i), str.length());
			}		
		}		
	}
### 题目描述 LeetCode Problem 46: **Permutations** 是一道中等难度的算法题目,主要任务是生成给定整数数组的所有可能的排列组合。例如,输入 `[1,2,3]` 应该输出以下排列结果: ``` [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ] ``` 该问题的核心在于生成所有可能的排列,且每个排列中的元素必须使用一次且仅使用一次[^4]。 --- ### 解题方法 #### 方法一:回溯法(递归) 这是一种常见的递归方法,通过维护一个布尔数组 `record` 来记录哪些元素已经被使用,然后递归地尝试将未使用的元素加入当前排列中。当当前排列长度与输入数组长度一致时,就将该排列加入结果集。 ```cpp class Solution { public: vector<vector<int>> permute(vector<int>& nums) { vector<vector<int>> res; vector<bool> record(nums.size(), false); vector<int> cur; per(res, record, cur, nums, nums.size(), 0); return res; } private: void per(vector<vector<int>>& res, vector<bool>& record, vector<int>& cur, vector<int>& nums, int n, int pos) { for (int i = 0; i < n; ++i) { if (!record[i]) { record[i] = true; cur.push_back(nums[i]); if (pos == n - 1) res.push_back(cur); else per(res, record, cur, nums, n, pos + 1); cur.pop_back(); record[i] = false; } } } }; ``` 这种方法的时间复杂度为 **O(n × n!)**,其中 `n!` 是所有排列的总数,而 `n` 是每个排列的构造时间[^3]。 --- #### 方法二:逐层构建排列 该方法基于这样一个观察:每个排列可以看作是在前 `n-1` 个数的排列基础上,将第 `n` 个数插入到每一个可能的位置。通过迭代的方式,逐层构建排列。 ```java public List<List<Integer>> permute(int[] nums) { List<List<Integer>> res = new ArrayList<>(); if (nums == null || nums.length == 0) return res; List<Integer> first = new ArrayList<>(); first.add(nums[0]); res.add(first); for (int i = 1; i < nums.length; i++) { List<List<Integer>> newRes = new ArrayList<>(); for (List<Integer> item : res) { for (int j = 0; j <= item.size(); j++) { List<Integer> temp = new ArrayList<>(item); temp.add(j, nums[i]); newRes.add(temp); } } res = newRes; } return res; } ``` 该方法的时间复杂度也为 **O(n × n!)**,但实现方式更为直观,适合理解排列的构建过程[^2]。 --- ### 相关问题 - **LeetCode 47: Permutations II** —— 处理包含重复元素的排列问题。 - **LeetCode 60: Permutation Sequence** —— 找出第 k 个排列。 - **LeetCode 31: Next Permutation** —— 实现下一个字典序排列。 - **LeetCode 77: Combinations** —— 生成所有可能的组合。 这些问题都与排列、组合密切相关,适合进一步巩固递归与回溯算法的使用[^1]。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值