7.23 permutation & nextpermu

to do

7.23 permutation & nextpermu_第1张图片

8.3.2 Next Permutation

reference to sth can not "repoint" like pointer does
实在写太久了哭。。mark

    void nextPermutation(vector& nums) {
        int pivoti = -1;
        // from R->L, find first occurence of out of order.(descending) if 1220, 1
        for (int i=nums.size()-1; i>0; --i) {
            if (nums[i-1] < nums[i]) {
                pivoti=i-1;
                break;
            }
        }
        if (pivoti==-1) {
            reverse(nums.begin(), nums.end());
            return;
        }
        
        // from R->L. find first occurence of greater than [pivoti]
        for (int j=nums.size()-1; j>=0; --j) {
            if (nums[j] > nums[pivoti]) {
                swap(nums[j], nums[pivoti]);
                // int tmp = nums[pivoti];
                // nums[pivoti] = nums[j];
                // nums[j] = tmp;
                reverse(nums.begin()+pivoti+1, nums.end());
                return;
            }
        }
    }

std::for_each

template  
Function for_each (InputIterator first, InputIterator last, Function fn);
**Apply function to range**
template  
Function for_each(InputIterator first, InputIterator last, Function fn) { 
  while (first!=last) { fn (*first); ++first; }
  return fn;// or, since C++11: return move(fn);
}

8.4.3] permutation II rec, 也可以用next permutation

或者看了答案的..感觉自己想的话,这个方法并不trivial。希望下次做的时候再明白透彻些。

有compiler问题,error required from here,ubuntu下次跑!
lambda func: [&reference_to_captured_var](params) {};

class Solution {
public:
    vector> permuteUnique(vector& nums) {
        sort(nums.begin(), nums.end());
        n = nums.size();
        // record occurences of each elem in map
        unordered_map map;
        for (auto i: nums) ++map[i];
        // convert map to vector of pair for tmp recording
        vector> record;
        // fn appy to each unordered_map entry, WHICH IS PAIR
        for_each(map.begin(), map.end(), [&record](pair& entry){ 
            record.push_back(entry);
        });        
        
        vector path;
        vector> ret;
        permuteR(record.begin(), record.end(), path, ret);
        return ret;
    }

private: 
    size_t n;
    void permuteR(vector>::iterator begin, vector>::iterator end, vector& path, vector>& ret) {
        if (path.size()==n) {
            ret.push_back(path);
            return;
        }
        // iterate through nums, if hasn't used up all occurrences of some elem, add and backtrack
        for (auto it=begin; it ct) {
                path.push_back((*it).first);
                permuteR(begin, end, path, ret);
                path.pop_back();
            }
        }
        
    }    
};

你可能感兴趣的:(7.23 permutation & nextpermu)