Subsets
Given a set of distinct integers, S, return all possible subsets.
Note:
- Elements in a subset must be in non-descending order.
- The solution set must not contain duplicate subsets.
For example,
If S = [1,2,3]
, a solution is:
[ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
思想:集合求解找递归关系。
注意事项: 在解决java问题时,要留意对引用的操作。
java代码:
- public ArrayList<ArrayList<Integer>> subsets(int[] S) {
- int len = S.length;
- ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
- ArrayList<Integer> cur = new ArrayList<Integer>();
- res.add(new ArrayList<Integer>(cur));
- if(len == 0) return res;
- Arrays.sort(S);//保证结果递增
- for(int i=0;i<len;i++) {
- int rlen = res.size();
- for(int j=0;j<rlen;j++) {
- ArrayList<Integer> tmp = new ArrayList<Integer>(res.get(j)); //如何直接获取,则操作的就是原引用
- tmp.add(S[i]);
- res.add(tmp);
- }
- }
- return res;
- }
C++代码: 更简洁,不存在引用的问题
- vector<vector<int> > subsets(vector<int> &S) {
- int N=S.size();
- sort(S.begin(),S.end());
- vector<vector<int> > res(1);
- for(int i=0;i<N;i++) {
- int j=res.size();
- while(j-- > 0) { // j=j-1 j>0
- res.push_back(res[j]);
- res.back().push_back(S[i]);
- }
- }
- return res;
- }
C++代码: 用bit求解
- vector<vector<int> > subsets(vector<int> &S) {
- int N=S.size();
- sort(S.begin(),S.end());
- vector<int> tmp;
- for(int i=0;i<pow(2,N);i++) {
- tmp.clear();
- for(int j=0;j<N;j++) {
- int exist = (i>>j) & 1;
- if(exist) {
- tmp.push_back(S[j]);
- }
- }
- res.push_back(tmp);
- }
- return res;
- }
C++: 用dfs求解,把tmp作为中间变量,不需要&
- vector<vector<int> > res;
- void subsetsHelper(vector<int> &S,vector<int> tmp,int cnt) {
- if(cnt == S.size()) {
- res.push_back(tmp);
- return;
- }
- subsetsHelper(S,tmp,cnt+1); // 0
- tmp.push_back(S[cnt]);
- subsetsHelper(S,tmp,cnt+1); //1,如果不行直接退出,tmp又恢复上一个值,并没有对上一个值进行改变
- }
- vector<vector<int> > subsets(vector<int> &S) {
- sort(S.begin(),S.end());
- vector<int> tmp;
- subsetsHelper(S,tmp,0);
- return res;
- }