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

来源:互联网 发布:学安卓软件开发教程 编辑:程序博客网 时间:2024/06/01 16:47

问题:
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;    }}
原创粉丝点击