全排列(递归)

/**
 *  1 2 2 3 4 5
 *  交换的方式
 */
public class Main
{
	static int count = 0;
	
    public static void main(String[] args)
	{
    	char[]arr = {'1','2','2','3','4','5'};
        dfs1(0,5,arr);
        System.out.println(count);
	}
    public static void dfs1(int start, int end, char[]arr) {
    	if (start == end) {
    		count++;
    		System.out.println(String.valueOf(arr));
    	}else {
    		for (int i = start; i <= end; i++) {
    			swap(start, i, arr);
    			dfs1(start+1, end, arr);
    			swap(start, i, arr);
    		}
    	}
    }
    public static void swap(int a, int b, char[]arr) {
    	char temp = arr[a];
    	arr[a] = arr[b];
    	arr[b] = temp;
    }
}
/**
 *  1 2 2 3 4 5     dfs深搜
 */
public class Test
{
	public static int count = 0;
	public static boolean[]flag = {false,false,false,false,false,false};
	public static char[]result;
	
    public static void main(String[] args)
	{
    	result = new char[6];
    	char[]arr = {'1','2','2','3','4','5'};
        dfs2(0,"",arr);
        System.out.println(count);
	}
    public static void dfs2(int index, String str, char[]arr) {
    	if (index == 6) {
    		System.out.println(String.valueOf(result));
    		count++;
    	}else {
	    	for (int i = 0; i < arr.length; i++) {
	    		if (flag[i] == false) {
	    			flag[i] = true;
	    			result[index] = arr[i];
	    			dfs2(index+1, str+arr[i], arr);
 	    			flag[i] = false;
	    		}
	    	}
    	}
    }
}

 

### C++ 实现全排列递归算法 以下是基于递归和回溯思想实现的 C++ 示例代码,能够输出给定字符串 `str` 的所有可能全排列: ```cpp #include <iostream> #include <string> using namespace std; // 定义递归函数,用于生成全排列 void permute(string& str, int start, int end) { // 如果起始位置等于结束位置,则表示找到一种排列方式 if (start == end) { cout << str << endl; return; } // 遍历当前位置及其后的字符,尝试每种可能性 for (int i = start; i <= end; ++i) { // 交换当前字符与其他字符 swap(str[start], str[i]); // 继续处理剩余部分 permute(str, start + 1, end); // 回溯:恢复原始状态以便进行下一次交换 swap(str[start], str[i]); } } int main() { string str = "abc"; // 输入字符串 int n = str.length(); // 字符串长度 permute(str, 0, n - 1); // 调用递归函数生成全排列 return 0; } ``` #### 解析 上述代码通过递归调用实现了字符串的全排列功能。核心逻辑如下: - 使用递归函数 `permute` 来逐步固定每一位上的字符,并对其余未固定的字符继续求解子问题[^3]。 - 每次递归前会交换两个字符以改变顺序,在完成递归后需再交换回来还原原状(即回溯操作)。这一步确保了每次递归结束后可以正确返回至上一状态并探索其他分支[^1]。 此程序对于输入 `"abc"` 将打印出六个不同的排列组合形式,分别是:"abc", "acb", "bac", "bca", "cab", 及 "cba"[^2]. ### 注意事项 为了防止重复计算或者错误结果,请注意以下几点: - **去重**:如果输入存在相同字母的情况,应考虑加入额外机制去除冗余项; - **边界条件检查**:确保传入参数有效性和合法性;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值