排列组合程序

本文探讨了排列组合的相关算法,包括Next Permutation、Permutation Sequence、Combinations、Subsets及其变种问题。通过实例解析并提供了源码,阐述了如何在给定条件下找出下一个排列、指定位置的排列序列、组合以及不重复和重复元素的子集。同时,讨论了去重情况下独特排列的生成方法。
摘要由CSDN通过智能技术生成

1.Next Permutation

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).

The replacement must be in-place, do not allocate extra memory.

Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,31,3,2
3,2,11,2,3

1,1,51,5,1

交换+排序

提供两个易错的例子:

1,4,3,2  -> 2,1,3,4

2,3,1  -> 3,2,1

代码如下:

public class Solution { 
        public static void nextPermutation(int[] nums){ 
        if(nums == null || nums.length < 2) return; 
        int pos = nums.length-1,i = pos-1; 
        while(i >= 0 && nums[i] >= nums[i+1]) i--; 
        if(i<0) {Arrays.sort(nums); return;} 
         
        for(;pos>i;pos--) if(nums[pos]>nums[i]) break; 
        swap(nums,i,pos); 
        Arrays.sort(nums,i+1,nums.length); 
    } 
    public static void swap(int[] nums,int i,int j){ 
        int tmp = nums[i]; 
        nums[i] = nums[j]; 
        nums[j] = tmp; 
    } 
}

2.Permutation Sequence


The set [1,2,3,…,n] contains a total ofn! unique permutations.

By listing and labeling all of the permutations in order,
We get the following sequence (ie, for n = 3):

  1. "123"
  2. "132"
  3. "213"
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值