一、Permutations
问题描述:
Given a collection of numbers, return allpossible permutations.
Forexample,
[1,2,3]
have thefollowing permutations:
[1,2,3]
, [1,3,2]
, [2,1,3]
, [2,3,1]
, [3,1,2]
, and [3,2,1]
.
问题分析:
假设给定数组为[1,2,3,4],根据递归的思想,则该4元素数组的排列组合是分别以1,2,3,4为首元素对剩下3个元素元素进行排列组合,也即将首元素分别与i = 0,1,2,3位置上的元素进行交换,进而对i+1—num.length-1这段数组进行排列组合;故形成了交换+递归的模式;
代码:
public class Solution { public List<List<Integer>> permute(int[] num) { List<List<Integer>> result = new ArrayList<>(); List<Integer> list = new ArrayList<>(); for (int i = 0; i < num.length; i++) list.add(num[i]); permute(list, 0, result); return result; } public void permute(List<Integer> list, int begin, List<List<Integer>> result) { // 添加结果值 if(begin >= list.size()) { result.add(list); return; } for(int i = begin; i < list.size(); i++) { // 实现的核心算法 swap(list, begin, i); // 注意list递归之后会发生变化,故这里产生相应副本进行操作 permute(new ArrayList<Integer>(list), begin + 1, result); } } // 交换List中的两个位置上的元素值 private void swap(List<Integer> list, int x, int y) { int temp = list.get(x); list.set(x, list.get(y)); list.set(y, temp); } }
二、Permutations II(有重复值)
问题描述:
Given a collection of numbers that mightcontain duplicates, return all possible unique permutations.
Forexample,
[1,1,2]
have thefollowing unique permutations:
[1,1,2]
, [1,2,1]
, and [2,1,1]
.
问题分析:
此题和前面的区别在于这里有了重复值,排列组合的核心算法仍和前面类似,只不过要处理重复值问题,避免与相同值进行重复交换;此外,值各不相同时可以不用考虑数组中的顺序,当有相同值时,要注意先进行排序,将相同值放到一起。
代码:
public class Solution { public List<List<Integer>> permuteUnique(int[] nums) { List<List<Integer>> result = new ArrayList<>(); List<Integer> list = new ArrayList<>(); // 当各个值互异时可以不用在意顺序;而有相同值时注意先排序将相同值放在一起 Arrays.sort(nums); // 初始化 for (int num : nums) list.add(num); permute(list, 0, result); return result; } private void permute(List<Integer> list, int i, List<List<Integer>> result) { if (i >= list.size() - 1) { result.add(list); return; } for (int k = i; k < list.size(); k++) { // 与前一题的唯一区别就是避免与重复值进行交换 if (k != i && list.get(i) == list.get(k)) continue; swap(list, i , k); permute(new ArrayList<Integer>(list), i + 1, result); } } private void swap(List<Integer> list, int a, int b) { int temp = list.get(a); list.set(a, list.get(b)); list.set(b, temp); } }
相关问题: