交换大法 全排列

//能排列重复的元素






public class Change {


/**
* @param args
*/

public static void main(String[] args) {
// TODO Auto-generated method stub
int a[]={1,1,2};
ch(a,0);
}
public static void ch(int a[],int start){
if(start==3){
for(int i=0;i<3;i++){
System.out.print(a[i]+" ");
}
System.out.println();
return;
}
for(int i=start;i<3;i++){
if(ok(a,start,i))
{
int temp=a[start];
a[start]=a[i];
a[i]=temp;
ch(a,start+1);
int temps=a[start];
a[start]=a[i];
a[i]=temps;
}
}
}
public static boolean ok(int b[],int start,int end){
for(int i=start;i<end;i++){
if(b[end]==b[i]){
return false;
}
}
return true;
}
}

### Python 字典序法实现全排列 字典序算法提供了一种非递归的解决方案,可以有效地按照字典顺序生成下一个排列。此方法特别适合于需要顺序输出或处理大数据量的情况[^1]。 #### 算法原理 为了理解字典序算法的工作机制,考虑如下步骤: - 找到最后一个升序对 `(i, i+1)`,即满足 `nums[i] < nums[i+1]` 的最大索引 `i`。 - 如果找不到这样的 `i`,则当前排列已经是最后一个排列;反之,则继续下一步。 - 接下来寻找从数组末尾向前第一个大于 `nums[i]` 的元素 `j` 并与其交换。 - 最后反转 `nums[i+1:]` 这一部分使得新得到的部分成为最小可能值。 #### 示例代码 下面是一个完整的 Python 函数来展示如何利用上述逻辑完成全排列的任务: ```python def next_permutation(nums): n = len(nums) # Step 1: Find the largest index k such that nums[k] < nums[k + 1]. k = -1 for i in range(n - 2, -1, -1): if nums[i] < nums[i + 1]: k = i break if k == -1: return False # This is already the last permutation. # Step 2: Find the largest index l greater than k such that nums[l] > nums[k], # and swap them. l = -1 for j in range(n - 1, k, -1): if nums[j] > nums[k]: l = j break nums[k], nums[l] = nums[l], nums[k] # Step 3: Reverse the sequence from nums[k + 1] up to and including the final element. left, right = k + 1, n - 1 while left < right: nums[left], nums[right] = nums[right], nums[left] left += 1 right -= 1 return True def generate_all_permutations(elements): elements.sort() result = [] while True: result.append(list(elements)) if not next_permutation(elements): break return result # Example usage: elements = ['a', 'b', 'c'] permutations = generate_all_permutations(elements) for p in permutations: print(''.join(p)) ``` 这段程序首先定义了一个辅助函数 `next_permutation()` 来找到并返回下一个更大的排列组合。如果不存在更大者,则表示已经到达最终状态,并返回 `False`。主函数 `generate_all_permutations()` 利用了这个特性不断调用直到无法再改变为止,从而收集到了所有的排列形式[^5]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值