Leetcode Permutation

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

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

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());
			}		
		}		
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值