Combinations(组合)

来源:互联网 发布:spine3.4 破解版 mac 编辑:程序博客网 时间:2024/06/06 18:11

题目

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],]

思路

递归函数:从 i 到 n 中选择 k 个元素,

分两种情况:

(1)选择第 i 个,则需要从 i+1 到 n 中选择 k-1个;

(2)不选择 i 个,则需要从 i+1 到 n 中选择 k个;

class Solution {public:    vector<vector<int> > combine(int n, int k) {        // Start typing your C/C++ solution below        // DO NOT write int main() function                vector<vector<int>> result;        vector<int> tmpv;        myfun(result, tmpv, 1, n, k);        return result;    }        void myfun(vector<vector<int>> &result, vector<int> &vec, int i, int n, int k)    {        if(k==0)            result.push_back(vec);              else if(i<=n)        {            vec.push_back(i);            myfun(result, vec, i+1, n, k-1);            vec.pop_back();              myfun(result, vec, i+1, n, k);                    }    }      };

 

最新 java

public class Solution {    public List<List<Integer>> combine(int n, int k) {        List<List<Integer>> result = new ArrayList<List<Integer>>();        List<Integer> list = new ArrayList<>();        combine(result, list, 1, n, k);        return result;    }        public void combine(List<List<Integer>> result, List<Integer> list, int cur, int n, int num) {        if(num == 0){            List<Integer> temp = new ArrayList<>();  // 注:这里需要重新建立对象List,否则添加进result的list会被修改            temp.addAll(list);            result.add(temp);        } else if(cur <= n){            list.add(cur);            combine(result, list, cur+1, n, num-1);            list.remove(list.size()-1);            combine(result, list, cur+1, n, num);        }    }    }

public class Solution {    public List<List<Integer>> combine(int n, int k) {        List<List<Integer>> result = new ArrayList<List<Integer>>();        List<Integer> list = new ArrayList<>();        combine(result, list, 1, n, k);        return result;    }    public void combine(List<List<Integer>> result, List<Integer> list, int cur, int n, int k) {        if(list.size() == k){            result.add(new ArrayList<>(list));        } else {            for(int i=cur; i<=n; i++){                list.add(i);                combine(result, list, i+1, n, k);                list.remove(list.size()-1);            }        }    }        // public void combine(List<List<Integer>> result, List<Integer> list, int cur, int n, int num) {    //     if(num == 0){    //         result.add(new ArrayList<>(list));    //     } else if(cur <= n){    //         list.add(cur);    //         combine(result, list, cur+1, n, num-1);    //         list.remove(list.size()-1);    //         combine(result, list, cur+1, n, num);    //     }    // }    }