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 {
public List<List<Integer>> permute(int[] nums) {
return helper(nums, 0);
}
public List<List<Integer>> helper(int[] nums, int offset) {
if (offset == nums.length) {
List<List<Integer>> result = new ArrayList<>();
result.add(new ArrayList<>());
return result;
}
List<List<Integer>> result = helper(nums, offset + 1);
List<List<Integer>> newResult = new ArrayList<>();
for (List<Integer> list : result) {
for (int i = 0; i < list.size() + 1; i++) {
List<Integer> newList = new ArrayList<>(list);
newList.add(i, nums[offset]);
newResult.add(newList);
}
}
return newResult;
}
}
原文:http://www.cnblogs.com/shini/p/4584851.html