题目:
给定一个 没有重复 数字的序列,返回其所有可能的全排列。
示例:
- 输入: [1,2,3]
- 输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
java:
public class Leetcode046 {
static List<List<Integer>> res = new ArrayList<>();
static LinkedList<Integer> path = new LinkedList<>();
static boolean[] used;
public static List<List<Integer>> permute(int[] nums) {
if (nums.length == 0) {
return res;
}
used = new boolean[nums.length];
permuteHelper(nums);
return res;
}
private static void permuteHelper(int[] nums) {
if (path.size() == nums.length) {
res.add(new ArrayList<>(path));
return;
}
for (int i = 0; i < nums.length; i++) {
if (used[i]) {
continue;
}
used[i] = true;
path.add(nums[i]);
permuteHelper(nums);
path.removeLast();
used[i] = false;
}
}
public static void main(String[] args) {
int[] nums = {1, 2, 3};
System.out.println(permute(nums));
}
}
Go:
package LeetCode
var (
result46 [][]int
path46 []int
used46 []bool
)
func Permute(nums []int) [][]int {
result46 = make([][]int, 0)
path46 = make([]int, 0, len(nums))
used46 = make([]bool, len(nums))
dfs46(nums, 0)
return result46
}
func dfs46(nums []int, cur int) {
if cur == len(nums) {
tmp := make([]int, len(nums))
copy(tmp, path46)
result46 = append(result46, tmp)
}
for i := 0; i < len(nums); i++ {
if !used46[i] {
path46 = append(path46, nums[i])
used46[i] = true
dfs46(nums, cur+1)
used46[i] = false
path46 = path46[:len(path46)-1]
}
}
}
func main() {
nums := []int{1, 2, 3}
permute := LeetCode.Permute(nums)
fmt.Println(permute)
}
吹凉的不是温度.
如果大家喜欢我的分享的话.可以关注我的微信公众号
念何架构之路