当前位置: 首页> 科技> IT业 > 46.全排列

46.全排列

时间:2025/7/13 0:17:54来源:https://blog.csdn.net/argcargv/article/details/140890661 浏览次数:0次

给定一个不含重复数字的数组 nums ,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。

class Solution {List<List<Integer>> res = new ArrayList<>();List<Integer> temp = new ArrayList<>();public List<List<Integer>> permute(int[] nums) {List<Integer> list = new ArrayList<>();backtrace(nums, list);return res;}// 用list记录添加过的下标。public void backtrace(int[] nums, List<Integer> list){if(list.size() == nums.length){res.add(new ArrayList(temp));return;}for(int i = 0; i < nums.length; i++){int num = nums[i];if(!list.contains(num)) {temp.add(num);list.add(num);} else continue;backtrace(nums, list);temp.remove(temp.size() - 1);list.remove(list.size() - 1);}}}

其实可以直接不记录list,使用nums不重复的特性,在temp中判断是否加入过某个元素:

class Solution {List<List<Integer>> res = new ArrayList<>();List<Integer> temp = new ArrayList<>();public List<List<Integer>> permute(int[] nums) {backtrace(nums);return res;}public void backtrace(int[] nums){if(temp.size() == nums.length){res.add(new ArrayList(temp));return;}for(int i = 0; i < nums.length; i++){// 因为nums不重复!int num = nums[i];if(!temp.contains(num)) {temp.add(num);} else continue;backtrace(nums);temp.remove(temp.size() - 1);}}   
}

关键字:46.全排列

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: