LeetCode46 Permutations

本文提供了一种解决LeetCode上第46题全排列问题的有效方法。通过使用递归搜索和回溯策略,实现了对整数数组的所有可能排列进行生成。文章包含了Java、C和Python三种语言的具体实现,每种实现都附有详细的注释说明。

详细见:leetcode.com/problems/permutations


Java Solution: github

package leetcode;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class P046_Permutations {
	public static void main(String[] args) {
		System.out.println(new Solution().permute(new int[] {1}));
	}
	/*
	 * 	全排列
	 * 	3 ms
	 * 	70.59% 
	 */
	static class Solution {
	    List<List<Integer>> ans = new LinkedList<List<Integer>>();
		public List<List<Integer>> permute(int[] nums) {
			if (nums == null || nums.length == 0)
				return ans;
	        Arrays.sort(nums);
	        search(nums, 0);
	    	return ans;
	    }
		private void search(int[] nums, int index) {
			if (index == nums.length) {
				List<Integer> answer = new LinkedList<Integer>();
				for (int i = 0; i != nums.length; i ++)
					answer.add(nums[i]);
				ans.add(answer);
			} else {
				for (int i = index; i < nums.length; i ++) {
					swap(nums, index, i);
					search(nums, index + 1);
					swap(nums, index, i);
				}
			}
		}
		private void swap(int[] nums, int i, int j) {
			int temp = nums[i];
			nums[i] = nums[j];
			nums[j] = temp;
		}
	}
}


C Solution: github

/*
    url: leetcode.com/problems/permutations/
    AC 9ms 20.00%
*/


#include <stdio.h>
#include <stdlib.h>

int* arr_copy_of(int* n, int ns) {
    int* ans = (int*) malloc(sizeof(int) * ns);
    int i = 0;
    for (i = 0; i < ns; i ++)
        ans[i] = n[i];
    return ans;
}

void swap(int* a, int* b) {
    int t = *a;
    *a = *b;
    *b = t;
}

void search(int** ans, int* ansIndex, int* n, int ni, int ns) {
    int i = 0;
    if (ni == ns) {
        ans[(*ansIndex) ++] = arr_copy_of(n, ns);
        return;
    }
    for (i = ni; i < ns; i ++) {
        swap(n+i, n+ni);
        search(ans, ansIndex, n, ni+1, ns);
        swap(n+i, n+ni);
    }
}

int** permute(int* n, int s, int* rs) {
    int len = 1, i = 0, ** ans = NULL, ansIndex = 0;
    for (i = s; i > 1; i --) len *= i;
    ans = (int**) malloc(sizeof(int*) * len);
    search(ans, &ansIndex, n, 0, s);
    *rs = len;
    return ans;
}

int main() {
    int n[] = {1, 2, 3};
    int s = 3;
    int rs = 0;
    int** ans = permute(n, s, &rs);
    int i = 0, j = 0;
    for (i = 0; i < rs; i ++) {
        for (j = 0; j < s; j ++)
            printf("%d ", ans[i][j]);
        printf("\r\n");
        free(*(ans+i));
    }
    free(ans);    
}


Python Solution: github

#coding=utf-8

'''
    url: leetcode.com/problems/permutations
    @author:     zxwtry
    @email:      zxwtry@qq.com
    @date:       2017年4月8日
    @details:    Solution: 89ms 33.38%
'''

class Solution(object):
    def swap(self, n, i, j):
        t = n[i]
        n[i] = n[j]
        n[j] = t
        
    def search(self, n, ans, i, nn):
        if i == nn:
            ans.append(list(n))
        for j in range(i, nn):
            self.swap(n, i, j)
            self.search(n, ans, i+1, nn)
            self.swap(n, i, j)
        
    def permute(self, n):
        """
        :type n: List[int]
        :rtype: List[List[int]]
        """
        nn, ans = 0 if n == None else len(n), []
        if nn == 0: return ans
        self.search(n, ans, 0, nn);
        return ans

if __name__ == "__main__":
    n = [1,2,3]
    ans = Solution().permute(n)
    print(ans)


### LeetCode46题 Python 实现 以下是针对LeetCode46题——Permutations的Python解决方案。该问题的核心在于生成给定列表的所有可能排列组合。 #### 方法一:回溯法 (Backtracking) 通过递归的方式构建每一种排列的可能性,使用`set()`或者布尔数组来标记已经使用的元素,从而避免重复计算。 ```python class Solution: def permute(self, nums: list[int]) -> list[list[int]]: result = [] def backtrack(path, remaining): if not remaining: # 如果剩余元素为空,则当前路径即为一个完整的排列 result.append(path[:]) return for i in range(len(remaining)): current_num = remaining[i] next_remaining = remaining[:i] + remaining[i+1:] path.append(current_num) # 将当前数字加入路径 backtrack(path, next_remaining) # 继续处理剩下的数字 path.pop() # 回溯,移除最后一个数字 backtrack([], nums) return result ``` 此方法的时间复杂度为O(N!),其中N为输入列表长度[^1]。 --- #### 方法二:插入法 (Insertion Method) 另一种思路是从空列表开始逐步扩展,每次将新数字插入已有排列的不同位置形成新的排列集合。 ```python class Solution: def permute(self, nums: list[int]) -> list[list[int]]: permutations = [[]] for num in nums: new_permutations = [] for permutation in permutations: for i in range(len(permutation) + 1): new_permutation = permutation[:i] + [num] + permutation[i:] new_permutations.append(new_permutation) permutations = new_permutations return permutations ``` 这种方法同样具有时间复杂度O(N!),但在某些场景下更直观易懂[^2]。 --- #### 方法三:DFS (Depth First Search) 利用深度优先搜索的思想,在每一层递归中选取尚未被固定的元素作为当前位置候选者,并继续向下探索直至完成整个序列的选择过程。 ```python class Solution: def permute(self, nums: list[int]) -> list[list[int]]: def dfs(ans, nums, path): if len(nums) == 0: ans.append(path) return for i in range(len(nums)): dfs(ans, nums[:i] + nums[i+1:], path + [nums[i]]) answer = [] dfs(answer, nums, []) return answer ``` 这种方式简洁明了,易于理解和实现[^3]。 --- ### 总结 以上三种算法均能有效解决LeetCode46题的要求,具体选择取决于个人偏好以及实际应用场景下的性能考量因素。无论是采用显式的状态维护还是隐含的状态传递机制,这些方案都能够满足题目对于不重复全排列生成的需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值