图解算法——全排列(Permutations)
1. 题目描述
Given an array nums
of distinct integers, return all the possible permutations. You can return the answer in any order.
2. Examples
示例1:
Input: nums = [0,1]
Output: [[0,1],[1,0]]
示例2:
Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
示例3:
Input: nums = [1]
Output: [[1]]
输入要求:
1 <= nums.length <= 6
-10 <= nums[i] <= 10
- All the integers of
nums
are unique.
3. 题目解析
思路:递归枚举
//全排列 /* 有两种思路:一是原地调换位置,二是树状分布 */ class Solution{ //数字全排列 public List<List<Integer>> permute(int[] nums) { List<List<Integer>> res = new List<List<Integer>>; List<Integer> arr = new ArrayList<Integer>; boolean[] is = new boolean(nums.length)//表示该下标所在字符是否存在:fasle表示不存在,true表示存在; search(res,arr,nums,is); return res; } public void search(List<List<Integer>> res, List<Integer> arr, int[] nums, boolean[] is){ if(arr.size() == nums.length){ res.add(arr); return; } for(int i = 0; i<nums.length; i++){ if(is[i]){ continue; } is[i] = true; arr.add(nums[i]); search(res,arr,nums,is); //是一个子问题 arr.remove(nums[i]); is[i] = false; } } //字符串全排列 public void permute1(string str) { char[] chs = str.toCharArray(); List<String> res = new ArrayList<String>; process(res,chs,0); } public void process(List<String> res, char[] chs,int i){ if(i==chs.length){ res.add(chs.toString()); return; } for(int j=i; j<chs.length; j++){ swap(chs,i,j); process(res,chs,++i); swap(chs,i,j); } } public void process(char[] chs,int i,int j){ int temp = chs[i]; chs[i] = chs[j]; chs[j] = temp; } }
还有类似的题目见:左神算法第八节课:介绍递归和动态规划
Over...