Leetcode 46-47. Permutations backtrack
来源:互联网 发布:影子网络杀人图 编辑:程序博客网 时间:2024/05/17 04:08
Leetcode 46. Permutations
理解: for 循环从0--n-1表示置换首位为1-n,动态规划问题,剩下的再进行全排列,for循环首句则判断是否为部分解,函授首句判断的是否为最终解,因为tmp一定是满足部分解,所以判断最终解部分只将检查大小就可以输出结果了。
注意点1:backtrack 里是否有指示位置的整型变量i
注意点2: new ArrayList<>(tmp) 而非直接tmp
import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class Solution { public List<List<Integer>> permute(int[] nums) { List<List<Integer>> res = new ArrayList<List<Integer>>(); Arrays.sort(nums); backtrack(res,new ArrayList<Integer>(),nums); return res; } private void backtrack(List<List<Integer>> res,List<Integer> tmp,int[] nums){ if(tmp.size()==nums.length){ res.add(new ArrayList<Integer>(tmp)); }else{ for(int i=0;i<nums.length;i++){ if(tmp.contains(nums[i])) continue; tmp.add(nums[i]); backtrack(res,tmp,nums); tmp.remove(tmp.size()-1); } } }}
47. Permutations II
这一题改动的只是在判断部分解时
import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class Solution { public List<List<Integer>> permuteUnique(int[] nums) { List<List<Integer>> res = new ArrayList<List<Integer>>(); Arrays.sort(nums); boolean[] used = new boolean[nums.length]; backtrack(res,new ArrayList<Integer>(),nums,used); return res; } private void backtrack(List<List<Integer>> res,List<Integer> tmp,int[] nums,boolean[] used){ if(tmp.size()==nums.length){ res.add(new ArrayList<Integer>(tmp)); }else{ for(int i=0;i<nums.length;i++){ if(used[i]||(i>0&&nums[i]==nums[i-1]&&used[i-1])) continue; used[i] = true; tmp.add(nums[i]); backtrack(res,tmp,nums,used); tmp.remove(tmp.size()-1); used[i] = false; } } }}
0 0
- Leetcode 46-47. Permutations backtrack
- LeetCode-46&47.Permutations
- LeetCode- 46/47. Permutations/Permutations || (JAVA) (全排列1,2)
- LeetCode 46 Permutations + LeetCode 47 Permutations II
- LeetCode 46/47. Permutations i, ii
- leetcode 46|47. Permutations 1|2
- [LeetCode]47.Permutations II
- LeetCode 47.Permutations II
- LeetCode --- 47. Permutations II
- [Leetcode] 47. Permutations II
- [leetcode] 47.Permutations II
- LeetCode 47. Permutations II
- 47. Permutations II LeetCode
- Leetcode 47. Permutations II
- LeetCode 47. Permutations II
- LeetCode - 47. Permutations II
- [LeetCode] 47. Permutations II
- leetcode 47. Permutations II
- 分析综合时出现Warning (12241): 1 hierarchies have connectivity warnings - see the Connectivity Checks repor
- DMG文件介绍及建立
- android 百度地图获取左上角和右下角的坐标
- gephi打开提示can't find java1.6 or higer
- html和css学习小结
- Leetcode 46-47. Permutations backtrack
- Java实例学习 Java并发编程之java.util.concurrent.CountDownLatch
- mac上可以使用的Windows远程桌面APP
- 闭包
- 最新全国身份证号码对照sql脚本
- 234. Palindrome Linked List
- as3 复制内容到剪贴板
- JAVA 数组常用方法
- 【Android-View】浅谈Android换肤的几种实现方式