leetCode 46.Permutations(排列组合) 解题思路和方法

来源:互联网 发布:淘宝开店图片怎么弄 编辑:程序博客网 时间:2024/04/30 20:36

Permutations

Given a collection of 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], and [3,2,1].


思路:本题是典型的排列组合的题,是经典算法。本文代码是由以前的封装的代码直接运用的,具体如下:

public class Solution {    boolean[] b;    List<List<Integer>> list;    List<String> al;    public List<List<Integer>> permute(int[] nums) {        b = new boolean[nums.length];        Arrays.fill(b,true);        list = new ArrayList<List<Integer>>();        al = new ArrayList<String>();        count(nums, "", nums.length);//全排列        //对al数据进行处理        for(String s : al){        List<Integer> newal = new ArrayList<Integer>();        for(int i = 0; i < s.length();i++){        if(s.charAt(i) == '-'){//有负号        newal.add('0' - s.charAt(++i) );        }else{//无负号        newal.add(s.charAt(i) - '0');        }        }        list.add(newal);        }        return list;    }    /**     *      * @param nums 要排列的数组     * @param str 已经排列好的字符串     * @param nn 剩下需要排列的个数,如果需要全排列,则nn为数组长度     */     void count(int[] nums,String str,int nn){        if(nn == 0){            al.add(str);//先添加到al中,再对al数据进行处理            return;        }        for(int i = 0; i < nums.length; i++){            if(b[i]){//如果还没有组合,则组合上                b[i] = false;//标记为已组合                count(nums,str + nums[i],nn-1);                b[i] = true;//为下一组合准备            }        }    }}


0 0