求全排列

无重复元素求全排列分递归和非递归版本

①递归版本

ABCD全排列 = A开头,BCD结尾的情况+B开头,ACD结尾的情况+C开头+D开头,就是第1个数跟后面的数交换

而A开头,BCD结尾的情况又可以递归处理,这时A已确定,对于BCD,再B分别和C、D交换...

当前数与后面的数交换得出全排列(下面代码是int的,可转为字符串)

C++版

void digui_next(int s1[],int cur,int n)
{
    if(n==cur)
    {
        output(s1,n);
    }
    else
    {
        for(int i=cur;i<n;i++)
        {
            swap(s1[i],s1[cur]);
            digui_next(s1,cur+1,n);
            swap(s1[i],s1[cur]);
        }
    }
}

JAVA版:

https://leetcode.com/problems/permutations/

class N46_Solution {
    //https://blog.csdn.net/u012469987/article/details/43090703
    private List<List<Integer>> ans;
    public List<List<Integer>> permute(int[] nums) {
        ans = new ArrayList<>();
        dfs(nums,0);
        return ans;
    }
    public void dfs(int[] nums,int cur) {
        if(cur == nums.length ){
            List<Integer> tempList = new ArrayList<>();
            for (int i = 0; i < nums.length; i++) {
                tempList.add(nums[i]);
            }
            ans.add(tempList);
            return;
        }

        for (int i = cur; i < nums.length; i++) {
            swap(nums,i, cur );
            dfs(nums,cur+1);
            swap(nums,i, cur );
        }
    }
    private void swap(int[] nums,int i,int j){
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}

public class N46_permutations {

    public static void main(String[] args) {
        int[] nums = new int[]{1,2,3};
        List<List<Integer>> list = new N46_Solution().permute(nums);
        System.out.println(list);
    }
}


②非递归版本

 

看这个,讲得实在不错 http://taop.marchtea.com/01.06.html

 

int fun(char *s1, int n) {
    int i = n - 2;
    while (i >= 0 && s1[i] >= s1[i + 1]) i--;
    if (i < 0) return false;
    int j = n - 1;
    while (j > 0  && s1[j] < s1[i]) j--;
    swap(s1[i], s1[j]);
    reverse(s1 + i + 1, s1 + n);
    return true;
}

 

 

 

 

 


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值