标签:cur 递归 int List DFS 问题 add dfs target
汉诺塔
-
题目地址:面试题 08.06. 汉诺塔问题
-
Java 代码
// 递归版本一 class Solution { public void hanota(List<Integer> A, List<Integer> B, List<Integer> C) { int n = A.size(); dfs(A, B, C, n); return; } private void dfs(List<Integer> a, List<Integer> b, List<Integer> c, int n) { if (n == 1) { c.add(a.remove(a.size() - 1)); } else { dfs(a, c, b, n - 1); c.add(a.remove(a.size() - 1)); dfs(b, a, c, n - 1); } } } // 递归版本二 class Solution { public void hanota(List<Integer> A, List<Integer> B, List<Integer> C) { int n = A.size(); dfs(A, B, C, n); return; } private void dfs(List<Integer> a, List<Integer> b, List<Integer> c, int n) { if (n == 1) { c.add(a.remove(a.size() - 1)); return; // 这里必须有,不然栈溢出! } dfs(a, c, b, n - 1); c.add(a.remove(a.size() - 1)); dfs(b, a, c, n - 1); } }
时间复杂度:\(O(2^n - 1)\),其中 \(n\) 为圆盘数量。
-
参考链接:
分支污染问题
理解 本贴 分支污染问题 和 递归分支污染对结果的影响。
-
Java 代码
// 体会分支污染问题 class Solution { public List<List<Integer>> combinationSum(int[] candidates, int target) { List<Integer> cur = new ArrayList<>(); dfs(cur, candidates, target); return res; } private void dfs(List<Integer> cur, int[] a, int target) { if (target == 0) { res.add(new ArrayList<>(cur)); return; } for (int i = 0; i < a.length; i++) { if (target < a[i]) continue; cur.add(a[i]); dfs(cur, a, target - a[i]); } } private List<List<Integer>> res = new ArrayList<>(); } // 解决分支污染问题 class Solution { public List<List<Integer>> combinationSum(int[] candidates, int target) { List<Integer> cur = new ArrayList<>(); dfs(cur, candidates, target); return res; } private void dfs(List<Integer> cur, int[] a, int target) { if (target == 0) { res.add(new ArrayList<>(cur)); return; } for (int i = 0; i < a.length; i++) { if (target < a[i]) continue; List<Integer> list = new ArrayList<>(cur); list.add(a[i]); dfs(list, a, target - a[i]); } } private List<List<Integer>> res = new ArrayList<>(); } // 也可以这样写 class Solution { public List<List<Integer>> combinationSum(int[] candidates, int target) { List<Integer> cur = new ArrayList<>(); dfs(cur, candidates, target); return res; } private void dfs(List<Integer> cur, int[] a, int target) { if (target == 0) { res.add(new ArrayList<>(cur)); return; } for (int i = 0; i < a.length; i++) { if (target < a[i]) continue; cur.add(a[i]); dfs(cur, a, target - a[i]); cur.remove(cur.size() - 1); // 利用回溯解决分支污染问题 } } private List<List<Integer>> res = new ArrayList<>(); }
体会
关键还是画出递归树,有递归树就很好写了。
标签:cur,递归,int,List,DFS,问题,add,dfs,target 来源: https://www.cnblogs.com/houhaibushihai/p/16302588.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。