这个回溯感觉掌握的有些熟练了。

两种方式,递归和循环。

感觉就是套框架了。

/**
 * Return an array of arrays of size *returnSize.
 * The sizes of the arrays are returned as *columnSizes array.
 * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
 */
int **ans;
int *col;
int cnt;

void back_track(int *a, int n, int k,int* last, int last_size)   //添加第k个元素
{
    if(k == n)
    {
        ans[cnt] = last;
        col[cnt] = last_size;
        cnt++;
        return;
    }
    int *cur = (int*)malloc(n*sizeof(int));
    memcpy(cur,last,last_size*sizeof(int));
    cur[last_size] = a[k];
    //不放k
    back_track(a,n,k+1,last,last_size);
    back_track(a,n,k+1,cur,last_size + 1);
}
int** subsets(int* nums, int numsSize, int** columnSizes, int* returnSize) {
    int n = pow(2,numsSize);
    ans = (int**)malloc(n*sizeof(int*));
    col = (int*)malloc(n*sizeof(int));
    cnt = 0;
    
    int *start = (int*)malloc(n*sizeof(int));
    back_track(nums,numsSize,0,start,0);
    
    *columnSizes = col;
    *returnSize = cnt;
    return ans;
}

 

class Solution {
public:
    vector<vector<int>> subsets(vector<int>& nums) {
        vector<vector<int>> ans;
        
        if(nums.size() == 0)
        {
            return ans;
        }

        vector<int> tmp;
        ans.push_back(tmp);
        
        for(int i = 0; i < nums.size(); i++)  //put ith
        {
            int cnt = ans.size();
            for(int k = 0; k < cnt; k++)
            {
                vector<int> tmp(ans[k]);
                tmp.push_back(nums[i]);
                ans.push_back(tmp);
            }
        }
        return ans;
    }
};

 

posted on 2017-12-12 22:03  newbird2017  阅读(161)  评论(0编辑  收藏  举报