赞
踩
Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.
Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
Input: nums = [0,1]
Output: [[0,1],[1,0]]
Input: nums = [1]
Output: [[1]]
From: LeetCode
Link: 46. Permutations
The basic idea behind this solution is a recursive backtracking approach to generate all possible permutations for the input array nums. At each step of the recursion, we consider each number in the array for the current position and then recursively generate permutations for the remaining numbers.
Key Components:
1. swap function:
This is a simple utility function that swaps two numbers in the array.
2. generatePermutations function:
This function is where the main logic resides. It takes the following parameters:
The logic works as follows:
3. permute function:
This is the main function that is called by the user. It sets up the necessary data structures and then calls generatePermutations to generate all permutations. The steps are:
/** * Return an array of arrays of size *returnSize. * The sizes of the arrays are returned as *returnColumnSizes array. * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). */ void swap(int* nums, int i, int j) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } void generatePermutations(int* nums, int numsSize, int start, int** result, int* returnSize) { if (start == numsSize) { result[*returnSize] = (int*)malloc(numsSize * sizeof(int)); for (int i = 0; i < numsSize; i++) { result[*returnSize][i] = nums[i]; } (*returnSize)++; return; } for (int i = start; i < numsSize; i++) { swap(nums, start, i); generatePermutations(nums, numsSize, start + 1, result, returnSize); swap(nums, start, i); // backtrack } } int** permute(int* nums, int numsSize, int* returnSize, int** returnColumnSizes) { int maxPermutations = 1; for (int i = 1; i <= numsSize; i++) { maxPermutations *= i; } int** result = (int**)malloc(maxPermutations * sizeof(int*)); *returnSize = 0; *returnColumnSizes = (int*)malloc(maxPermutations * sizeof(int)); for (int i = 0; i < maxPermutations; i++) { (*returnColumnSizes)[i] = numsSize; } generatePermutations(nums, numsSize, 0, result, returnSize); return result; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。