Combinations & Permutations (1.II)
Combinations
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], ]
思路一: 典型的DFS,遍历所有的路径,找到满足要求的结果
代码一:
- ArrayList<ArrayList<Integer> > res = new ArrayList<ArrayList<Integer> >();
- ArrayList<Integer> cur = new ArrayList<Integer>();
- public void helper(int start,int n,int k,int len) {
- if(len>=k) {
- if(len==k) {
- res.add(new ArrayList<Integer>(cur));
- }
- return;
- }
- for(int i=start;i<=n;i++) {
- cur.add(i);
- helper(i+1,n,k,len+1);
- cur.remove(cur.size()-1);
- }
- }
- public ArrayList<ArrayList<Integer> > combine(int n, int k) {
- if(k>n) return res;
- if(n==0) return res;
- if(k==0) return res;
- helper(1,n,k,0);
- return res;
- }
C++实现代码:
- vector<vector<int> > res;
- void combineHelper(vector<int> & cur,int start,int end,int n) {
- if(cur.size()==end) {
- res.push_back(cur);
- return;
- }
- for(int i=start;i<=n;i++) {
- cur.push_back(i);
- combineHelper(cur,i+1,end,n);
- cur.pop_back();
- }
- }
- vector<vector<int> > combine(int n, int k) {
- vector<int> cur;
- combineHelper(cur,1,k,n);
- return res;
- }
思路二: 用递归的思想求解,类似于Permutations
代码:
- vector<vector<int> > combine(int n, int k) {
- vector<vector<int> > res;
- vector<vector<int> > vec(1);
- vector<int> tmp;
- int len=0;
- for(int i=1;i<=n;i++) {
- len=vec.size();
- for(int j=0;j<len;j++) {
- tmp=vec[j];
- tmp.push_back(i);
- if(tmp.size()==k) res.push_back(tmp);
- else vec.push_back(tmp);
- }
- }
- return res;
- }
Permutations
在前面几种方法的基础上,可以用递归的思想求解,要学会选用合适的数据结构,(开始选用了ArrayList,没有合理的结合permute(int[] num)函数,导致了int[]和ArrayList之间返回转换。
- public ArrayList<ArrayList<Integer> > permute(int[] num) {
- Arrays.sort(num);
- ArrayList<ArrayList<Integer> > res = new ArrayList<ArrayList<Integer> >();
- ArrayList<ArrayList<Integer> > subres = new ArrayList<ArrayList<Integer> >();
- int n = num.length;
- ArrayList<Integer> newList = new ArrayList<Integer>();
- if(n==0) return res;
- if(n==1) {
- newList.add(num[0]);
- res.add(newList);
- return res;
- }
- for(int i=0;i<n;i++) {
- if(i>=1 && num[i]==num[i-1]) continue; // 注意去除重复项
- int tmp = num[i];
- num[i]=num[0];
- num[0]=tmp;
- int[] new_num = Arrays.copyOfRange(num,1,num.length); // 数组复制
- subres = permute(new_num);
- for(int j=0;j<subres.size();j++) {
- subres.get(j).add(num[0]);
- }
- res.addAll(subres);
- tmp = num[i];
- num[i]=num[0];
- num[0]=tmp;
- }
- return res;
- }
Permutations II (和Permutations 基本一致,去除重复项即可)
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
For example,[1,1,2] have the following unique permutations:[1,1,2], [1,2,1], and [2,1,1].

浙公网安备 33010602011771号