Combinations leetcode java
生活随笔
收集整理的這篇文章主要介紹了
Combinations leetcode java
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
題目:
Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
For example,
If n = 4 and k = 2, a solution is:
?題解:
?這道題就是用DFS(參考Work BreakII)的循環(huán)遞歸處理子問題的方法解決。n為循環(huán)的次數(shù),k為每次嘗試的不同數(shù)字。用到了回溯。
?代碼如下:
?
?1?????public?ArrayList<ArrayList<Integer>>?combine(int?n,?int?k)?{?2?????????ArrayList<ArrayList<Integer>>?res?=?new?ArrayList<ArrayList<Integer>>();
?3?????????if(n?<=?0||n?<?k)
?4?????????????return?res;
?5?????????ArrayList<Integer>?item?=?new?ArrayList<Integer>();????
?6?????????dfs(n,k,1,item,?res);//because?it?need?to?begin?from?1
?7?????????return?res;
?8?????}
?9?????private?void?dfs(int?n,?int?k,?int?start,?ArrayList<Integer>?item,?ArrayList<ArrayList<Integer>>?res){
10?????????if(item.size()==k){
11?????????????res.add(new?ArrayList<Integer>(item));//because?item?is?ArrayList<T>?so?it?will?not?disappear?from?stack?to?stack
12?????????????return;
13?????????}
14?????????for(int?i=start;i<=n;i++){
15?????????????item.add(i);
16?????????????dfs(n,k,i+1,item,res);
17?????????????item.remove(item.size()-1);
18?????????}
19?????}
Reference:http://blog.csdn.net/linhuanmars/article/details/21260217
?
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的Combinations leetcode java的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Discuz! 在线中文分词、关键词提取
- 下一篇: cube、rollup及exec的用法实