Permutations:排列

来源:互联网 发布:迅雷7优化版 编辑:程序博客网 时间:2024/06/05 19:10

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]]
思路:这种题一定是递归,因为要给出所有方式,有一点特殊的是使用一个arraylist来暂存结果。!!!做了有一阵题了,这种简单题还是没做出来,惆怅。


class Solution {        public void dfs(List<List<Integer>> list,List<Integer> l,int[] nums){        if(l.size()==nums.length){            list.add(new ArrayList<Integer>(l));            return;        }else{            for(int i=0;i<nums.length;i++){                if(l.contains(nums[i])) continue;                l.add(nums[i]);                dfs(list,l,nums);                l.remove(l.size()-1);            }        }    }        public List<List<Integer>> permute(int[] nums) {       List<List<Integer>> list = new ArrayList<List<Integer>>();       dfs(list,new ArrayList<Integer>(),nums);       return list;    }}



原创粉丝点击