https://leetcode.com/problems/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 {
public List<List<Integer>> permute(int[] num) {
List<List<Integer>> rst = new LinkedList<List<Integer>>();
if(num==null || num.length==0) return rst;
List<Integer> pmt = new LinkedList<Integer>();
HashSet<Integer> index = new HashSet<Integer>();
helper(num, rst, pmt, index);
return rst;
}
public void helper(int[] num, List<List<Integer>> rst, List<Integer> pmt, HashSet<Integer> index){
if(pmt.size()==num.length){
rst.add(new LinkedList<Integer>(pmt));
return;
}
if(pmt.size() > num.length) return;
for(int i=0; i<num.length; i++){
if(index.contains(i)) continue;
pmt.add(num[i]);
index.add(i);
helper(num, rst, pmt, index);
index.remove(i);
pmt.remove(pmt.size()-1);
}
}
}
本文介绍了使用递归算法解决排列问题的方法,并提供了具体的代码实现。通过实例演示了如何找到给定数字集合的所有可能排列。
315

被折叠的 条评论
为什么被折叠?



