216. Combination Sum III
生活随笔
收集整理的這篇文章主要介紹了
216. Combination Sum III
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
/** 216. Combination Sum III * 2016-6-12 by Mingyang* i一定要取到9,雖然大小聰明,想只取到7,但是后面的遍歷可能也會遍歷到9啊。* 1.長度標準:無(固定等于k)* 2.可選的范圍:從start開始到9* 3.往前走一步:temp加入這個數,k-1表示又來了一位,n-i,然后i加1表示從下一位加起* 4.后退一步:temp減去這個數* 5.特別的case:剩下的小于0直接return* 6.關于重復:11 和1 在第一個1用了以后,第二個1就不用了* 錯誤點1:自己做的時候不知道i加到多少,題目已經明確說過到9就好了* 錯誤點2:就是下一輪dfs的start為i加1不是start加1*/public static List<List<Integer>> combinationSum3(int k, int n) {List<List<Integer>> res = new ArrayList<List<Integer>>();List<Integer> temp = new ArrayList<Integer>();dfs(res, temp, k, n, 1);return res;}public static void dfs(List<List<Integer>> res, List<Integer> temp, int k, int n,int start) {if (k == 0) {if (n == 0) {res.add(new ArrayList<Integer>(temp));}return;}for (int i = start; i <= 9; i++) {temp.add(i);dfs(res, temp, k - 1, n - i, i+1);//這個地方非常容易錯,就是下一個是i加1!!!!并不是start+1!!!!!!!!!!!!!!!!temp.remove(temp.size() - 1);}}
?
轉載于:https://www.cnblogs.com/zmyvszk/p/5579302.html
總結
以上是生活随笔為你收集整理的216. Combination Sum III的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: js接受url参数
- 下一篇: HTML5新增标签的汇总与详解