LeetCode刷题笔录Combinations
来源:互联网 发布:淘宝首页如何装修全屏 编辑:程序博客网 时间:2024/06/05 10:50
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:
[ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4],]
这题和Permutations这题差不多。注释里写了想法。
在这里有一个更详尽的说明。
public class Solution { public ArrayList<ArrayList<Integer>> combine(int n, int k) { ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); if(n == 0 || k == 0) return result; recursive(result, n, k, new ArrayList<Integer>(), 1); return result; } public void recursive(ArrayList<ArrayList<Integer>> result, int n, int k, ArrayList<Integer> oneSolution, int start){ //the current arraylist has the size of k, go to next solution if(oneSolution.size() == k){ result.add(new ArrayList<Integer>(oneSolution)); return; } for(int i = start; i <= n; i++){ oneSolution.add(i); //the next number should be larger thank the previous number //i.e., if the first digit is 1, then the second digit can only be 2, 3, 4,...n //this is reflected by incrementing start in the recursive call recursive(result, n, k, oneSolution, start + 1); //remove the last trial digit and try the next //if [1,2,x](x from 3 to n) is tried, remove the 2, try from [1,3,x] oneSolution.remove(oneSolution.size() - 1); } }}
0 0
- LeetCode刷题笔录Combinations
- LeetCode刷题笔录Letter Combinations of a Phone Number
- Leetcode刷题笔录 Anagrams
- LeetCode刷题笔录 Permutaions
- LeetCode刷题笔录Subsets
- LeetCode刷题笔录Triangle
- LeetCode刷题笔录LRUCache
- LeetCode刷题笔录 Two Sum
- LeetCode 刷题笔录 Add Two Numbers
- LeetCode刷题笔录 Reverse Integer
- LeetCode刷题笔录 Reorder List
- LeetCode刷题笔录 Jump Game II
- LeetCode刷题笔录 Search Insert Position
- LeetCode刷题笔录 Pow(x,n)
- LeetCode刷题笔录 Rotate List
- LeetCode刷题笔录 Single Number
- LeetCode刷题笔录 Same Tree
- LeetCode刷题笔录Linked List Cycle
- map类简说
- java堆空间(内存)
- 程序员生存定律--使人生永动的势能
- 如何将PDF转换成PPT文件
- ABB 机器人 IsStopMoveAct 指令 - Is stop move flags active
- LeetCode刷题笔录Combinations
- mysql 连接时的错误
- 关于MultipeerConnectivity
- CentOS7下源码安装MariaDB10.0.12
- 动态数组的实现
- 云计算- 概念,构架和挑战
- c# 获取文件名称
- MyEclipse安装FreeMarker插件
- POJ_1985_Cow Marathon(树的直径)