字符串算法——数组或字符串全排列(Permutations)

问题:
Given a collection of distinct numbers, return all possible permutations.

For example,
[1,2,3] have the following permutations:

[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]

这里无重复字符元素
解决思路:可以使用递归的方法来解决该问题,不断对元素进行位置交换

class Solution {
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        dfs(res,nums,0);//递归函数
        return res;
    }
    //
    private void dfs(List<List<Integer>> res,int []nums,int j){
        if(j==nums.length){
            List<Integer>temp = new ArrayList<>();//存储每一次交换后的序列
            for(int num:nums)temp.add(num);
            res.add(temp);
        }
        //索引位置递归交换
        for(int i = j;i<nums.length;i++){
            swap(nums,i,j);
            dfs(res,nums,j+1);
            swap(nums,i,j);
        }
    }  
    //交换函数
    private void swap(int[]nums,int m,int n){
        int temp = nums[m];
        nums[m]= nums[n];
        nums[n] = temp;
    }
}

思路二:采用非递归的方法,可以使用插入法
例如:数组为[1,2,3],先取第一个元素1,然后取得第二个元素进行插入得到[1,2]或者[2,1],再对其插入可以得到[3,1,2]、[1,3,2]、[1,2,3]、[3,2,1]、[2,3,1]、[2,1,3]

class Solution {
    public List<List<Integer>>permute1(int []nums){
         List<List<Integer>> res = new ArrayList<>();//存储全排列后数组
         ArrayList<Integer> first = new ArrayList<>();
         first.add(nums[0]);//存储首位置元素
         res.add(first);//存放第一个列表对象
         for(int i= 1;i<nums.length;i++){
            List<List<Integer>> newRes = new ArrayList<>();//存放每次插入新值的列表对象
            for(List<Integer> temp:res){//待插入新值得序列对象
                int size = temp.size()+1;
                for(int j = 0;j<size;j++){
                    List <Integer>item = new ArrayList<>(temp);//暂存待插入的序列对象
                    item.add(j,nums[i]);//插入新值
                    newRes.add(item);//更新
                }
            }
            res = newRes;
        }
        return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值